How to write unit tests with TPL and TaskScheduler

后端 未结 5 1580
离开以前
离开以前 2021-02-01 06:50

Imagine a function like this:

private static ConcurrentList list = new ConcurrentList();
public void Add(object x)
{
   Task.Factory.         


        
      
      
      
5条回答
  •  醉酒成梦
    2021-02-01 07:17

    For at least most simple-ish cases, I like to use an "expiring" assertion for this sort of thing. e.g.:

    YourCollection sut = new YourCollection();
    
    object newItem = new object();
    sut.Add(newItem);
    
    EventualAssert.IsTrue(() => sut.Contains(newItem), TimeSpan.FromSeconds(2));
    

    where EventualAssert.IsTrue() looks something like this:

    public static void IsTrue(Func condition, TimeSpan timeout)
    {
        if (!SpinWait.SpinUntil(condition, timeout))
        {
            Assert.IsTrue(condition());
        }
    }
    

    I also generally add an override with a default timeout which I use for most of my tests, but ymmv...

提交回复
热议问题