testing method which create a new thread and result we get from event ( NUnit 2.6 )

后端 未结 4 650
别那么骄傲
别那么骄傲 2021-02-10 01:26

I have class which have one public method Start, one private method and one event Finishing. Start call new Thread( private_method )

4条回答
  •  再見小時候
    2021-02-10 01:28

    As mentioned you can unit test multi threaded components but it is not clean like regular unit tests. I have mostly encountered it in Acceptance Tests and have had great success with the .net 4 Task and Parallel classes. However in this case a simple sleep might get you going but if you start doing lots of these tests you might want a more performant way of doing it.

    [Test]
    public void Test1()
    {
        bool wasCalled = false;
    
        SomeClass someObject = new SomeClass();
    
        someObject.Finishing += new SomeClass.FinishingEventHandler((sender, a) =>
        {
            wasCalled = true;
        });
        someObject.Start(); // when this method will finish, then call event Finishing
    
        Thread.Sleep(2000);
    
        Assert.True(wasCalled);
    }
    

    What ever you do you need some timeout somewhere that will cause the test to finish instead of hanging forever, this could be done in the test itself or some test libraries have a Timeout attribute you can decorate the test with.

提交回复
热议问题