xUnit: how to Assert other event of types then EventHandler<EventArgs>

点点圈 提交于 2021-01-04 10:35:05

问题


I'm a beginner in unit testing and I've been searching the net for couple of hours now and I still can't find the answer to my simple question.

I have a class with the following event:

event Action<ITagData> OnTagHandled

Now I want to write a unit test to assert if the event has been raised but when I write something like:

Assert.Raises<EventArgs>(handler => m_rssiHander.OnTagHandled += handler,
    handler => m_rssiHander.OnTagHandled -= handler, () => { });

I get an error like:

Cannot implicitly convert type System.EventHandler to System.Action

Can someone tell me how I can assert an event of type Action<T>?


回答1:


It is because handler is type of EventHandler<EventArgs> so m_rssiHander.OnTagHandled += handler will not work

you will have to change: event Action<ITagData> OnTagHandled

TO event Action<EventArgs> OnTagHandled for it to work or any child class of EventArgs and inherit ITagData interface

e.g.

class TagDataEventArgs: EventArgs, ITagData {}

and use it as: event Action<TagDataEventArgs> OnTagHandled

AND assert:

Assert.Raises<TagDataEventArgs>(handler => m_rssiHander.OnTagHandled += handler,
        handler => m_rssiHander.OnTagHandled -= handler, () => { });



回答2:


Finally I decided to do it like this:

 bool wasEventRaised = false;
 m_rssiHandler.OnTagHandled += data => { wasEventRaised = true;};

 // Act
 m_rssiHandler.ProcessTag(m_tag);

 // Assert
 Assert.True(wasEventRaised);


来源:https://stackoverflow.com/questions/52956862/xunit-how-to-assert-other-event-of-types-then-eventhandlereventargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!