Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit Assert event .Any suggestions?

Wondering if this is the correct way to test result with events.

I am working on a application that when Save is in progress/completed it fires events.

In order to test it I have come up with the following (Made up scenario). And I'm wondering if this is the way you do it:

[Test]
public void Save_WhenCalled_IsSuccessfull()
{
    //Arrange
    var customerService= new CustomerService();

    customerService.OnSaved += (sender, args) =>
        {                                             
            Assert.IsTrue(args.HasSaved);
        };

    customerService.Save(new Customer {Id=1,Name="Jo"});
}

What I dont like is that I am asserting before if you see what I mean.

I would like the assert to be visually last. By the way the above works just fine, but not quite happy.

Any suggestions?

like image 329
user9969 Avatar asked Mar 18 '26 18:03

user9969


1 Answers

Looks good, but you should store the received parameters (or any other check) in a variable in order to keep the arrange/act/assert sequence. That way you also assert that the event has actually fired, something your example does not verify.

[Test]
public void Save_WhenCalled_IsSuccessfull()
{
    //Arrange
    YourArgsType actualArgs;
    var customerService= new CustomerService();  
    customerService.OnSaved+= (sender, args) =>
                                  {                                           
                                      actualArgs = args;
                                  };

    //Act
    customerService.Save(new Customer{Id=1, Name="Jo"});

    //Assert
    Assert.IsTrue(actualArgs.HasSaved);
}

EDIT: Added Alexander suggestion.

like image 198
istepaniuk Avatar answered Mar 20 '26 06:03

istepaniuk