3

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?

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
user9969
  • 15,632
  • 39
  • 107
  • 175
  • Have you looked into this ? -> http://stackoverflow.com/questions/248989/unit-testing-that-an-event-is-raised-in-c-sharp – Dimitar Dimitrov Jan 27 '13 at 16:31
  • @DimitarDimitrov seen now,I see that the difference is that he creates a list and adds all the events there, and then he queries the list in the assert.Is that correct?.Should I create a dictionary EG PropertyName,Value and then query it? is that a better way to do it – user9969 Jan 27 '13 at 16:39
  • @user231465, according to the name of your test method, that would not be necessary in this case. It helps to keep the test as simple as possible. – istepaniuk Jan 27 '13 at 16:44

1 Answers1

5

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.

istepaniuk
  • 4,016
  • 2
  • 32
  • 60