user9969
user9969

Reputation: 16040

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?

Upvotes: 3

Views: 1606

Answers (1)

istepaniuk
istepaniuk

Reputation: 4271

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.

Upvotes: 5

Related Questions