Reputation: 8415
I have defined two events with custom event arguments and associated raising methods. Now I wonder what and how the event should be tested. How should I analyze the code to find candidates for unit testing?
Upvotes: 4
Views: 1056
Reputation: 21365
The way I test events is as follows:
Suppose this is your object:
public class MyEventRaiser
{
public event EventHandler<string> MyEvent = delegate { };
public void Process(string data)
{
// do something interestuing
Thread.Sleep(2000);
if (!string.IsNullOrEmpty(data))
{
this.MyEvent(this, data + " at: " + DateTime.Now.ToString());
}
}
}
Therefore your Subject Under Test is: MyEventRaiser
and you want to test the method Process
. You need to test that the event is raised when certain conditions are met, otherwise, the event should not be raised.
To do it, I use this framework (that I use always in my tests) FluentAssertions, this framewrok can be used with any test engine like MSTest, NUnit, MSpec, XUnit, etc
The tests look like:
[TestClass]
public class CustomEventsTests
{
[TestMethod]
public void my_event_should_be_raised()
{
var sut = new MyEventRaiser();
sut.MonitorEvents();
sut.Process("Hello");
sut.ShouldRaise("MyEvent").WithSender(sut);
}
[TestMethod]
public void my_event_should_not_be_raised()
{
var sut = new MyEventRaiser();
sut.MonitorEvents();
sut.Process(null);
sut.ShouldNotRaise("MyEvent");
}
}
You need to use the following namespaces:
using FluentAssertions;
using FluentAssertions.EventMonitoring;
Upvotes: 4