问题
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