dbones notes
its a geek thing

Mocking a void function, and ensuring it was called

June 25, 2009 22:59 by Dave

One thing I wanted to do was to ensure my code was calling a function with the correct inputs. However the function did not return anything (void) and I did not want to write a mock object from scratch which had a verify method was called (that seemed like re-writing the wheel). So I looked a little into Rhino Mocks (Ayende, you are a genius!), low and behold you can do this with this framework (quite easily)

Project Files TestVoidMethodMocking.rar (128.38 kb)  (VS 2008, using MBUnit)

Ok lets quickly look at what I am doing. I have a Interface, for sending emails.

public interface IEmailService
{
    void SendEmail(string subject, string body);
}

And I have a class which has an Update() method, which calls this method (when the State changes from State.One to State.Two), as follows

public void Update()
{
    switch (currentState)
    {
        case State.One:
            if (form.ProcessedState == State.Two)
            {
                EmailService.SendEmail("Status Change", string.Format("Form {0} has entered state 2", form.Name));
            }
            break;
        case State.Two:
            break;
        case State.Three:
            break;
        default:
            break;
    }
}

Within the Test project, I would like to verify that the SendEmail() method is being called with the correct information. So I have used Rhino Mocks Expect.Call to ensure this. For this test I am going to have a form.Name = "test", so I will expect the method call to look like

SendEmail("Status Change", "Form test has entered state 2")

Here is the Unit Test Code: 

[Test]
public void TestIfEmailWasCalledCorrectly()
{
    //Record
    var mocks = new MockRepository();
    IEmailService emailService = mocks.DynamicMock<IEmailService>();
    Expect.Call(() => emailService.SendEmail("Status Change", "Form test has entered state 2"));
    mocks.ReplayAll();

    //Arrange
    Form form1 = new Form()
    {
        Name = "test",
        Message = "test1",
        ProcessedState = State.One,
    };

    StateNotification sn = new StateNotification(form1);
    sn.EmailService = emailService;

    //Action
    form1.ProcessedState = State.Two;
    sn.Update(); //message was sent

    //Assert
    mocks.VerifyAll();
}

 

now when I run the test. I get all green


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: Test
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Comments