How should events be tested in ASP.Net?

I defined two events with custom event arguments and related promotion methods. Now I wonder what and how to test. How can I analyze the code to find candidates for unit testing?

+4
source share
1 answer

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()); } } } 

So your subject is under test: MyEventRaiser , and you want to test the Process method. You need to check that the event occurs when certain conditions are met, otherwise the event should not be raised.

For this, I use this framework (I always use it in my tests ) FluentAssertions , this framewrok can be used with any test engine, such as MSTest, NUnit, MSpec, XUnit, etc.

The tests look like this:

 [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; 
+4
source

Source: https://habr.com/ru/post/1437078/


All Articles