简体   繁体   中英

Assert if event gets are fired within a Unit Test

I need to check if an object (EventTrigger) fires events and if I receive the expected data via the EventArgs via a unit test. In order to do that id like to loop the entire sequence for hundreds of times within my test method to assert against the event to check if the the event gets fired every time and if i get the correct data.

Yes, I'm fully aware that this is not a real Unit Test, its an integration test. But the actual events get triggered by some involved hardware and that's what I aim to test.

The problem that I have is that the test fails because the event does not get fired. But the strange thing is that it fails randomly. Sometimes after 2,50, 80,200 or whatever number of iterations.

So I suspect that somehow the reference to my event handler gets lost. I read a lot about async/await etc. but I couldn't figure out how to use it in this case.

    [TestMethod]
    public void FireEvents_CheckIfCorrectEventsFired_ReturnTrue()
    {
        AutoResetEvent eventFired = new AutoResetEvent(false);
        int i = 1, sum =0;

        EventTrigger.VariableChanged += (s, e) =>
        {
            if (e.VarInfo.Name.Contains("foo1"))
            {
                sum = 1;
                eventFired.Set();
            }
            else if (e.VarInfo.Name.Contains("bar2"))
            {
                sum = 2;
                eventFired.Set();
            }
        };

        while (true)
        {
            TriggerEvents();
            Assert.IsTrue(eventFired.WaitOne(3000));
            Assert.IsTrue((sum ==1) || (sum ==2));
            eventFired.Reset();
            i++;

            if (i == 100)
                break;
        }
    }

    private void TriggerEvents()
    {
      // Long running process triggering events based on external hardware
    }

EDIT: The event gets triggered on another object in this way:

Volatile.Read(ref VariableChanged)?.Invoke(this, new VariableChangedEventArgs(varInfo));

So basically if the HW module triggers a variable change this event gets fired and holds the information.

I have tested all in detail and the event gets definitely fired and the data provided by the EventArgs are correct. Its just that in my test class (consumer) sometimes doesn't handle the event. I thought it could be that the reference to the event handler gets lost or whatever.

I simplified the code here because the actual code involves a lot of stuff that is not relevant for the actual problem. I banged my head on this for a while and couldn't find a way to solve my problem.

我不确定这是否重要,但通常不必为AutoResetEvent调用Reset()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM