2
votes

I need some assistance with writing a unit test for the following class using Rhino Mocks 3.5. The following overrided method in my class:

    public override void Initialize(params object[] messages)
    {
        var data = new ViewData
        {
            Name = this.GetName()
        };

        this.Notify(data);
    }

I want to be write a test to validate that when the Initialize method is called, the method calls the Notify method and has a parameter of type ViewData. Also I want to check that the GetName method which is a private method is called within this method. I use an accessor to access the GetName private method.

Any help would be great with this as I am new to writing tests and need assistance.

2
What method Notify() does? Does it access somehow any other classes which injected in this class?sll
What are the signatures of GetName() and Notify()? If Notify only accepts a ViewData, you don't need to write a unit test to verify that the parameter is of type ViewData -- .NET will enforce that for you at compile time.PatrickSteele

2 Answers

3
votes

What you want is called a partial mock.

[Test]
public void UsingPartialMocks()
{
  MockRepository mocks = new MockRepository();
  YourClass partialMock =  mocks.PartialMock<YourClass>();
  Expect.Call(partialMock.Notify(null)).IgnoreArguments();
  mocks.ReplayAll();
  partialMock.Initialize(null);
  mocks.VerifyAll();
}
0
votes

While not directly answering your question on how to do it using Rhino (it appears that Jon has done a decent job at that already), for posterity sake I'll show how I would test it using manual mocking. (bear with me, it's been a while since I've done C#, so pardon the syntax errors)

[Test]
public void initializeRegistersViewDataWithGivenName()
{
  ShuntedYourClass yourClass = new ShuntedYourClass();
  yourClass.initialize( /* arg list */ );

  // Verify 'Notify' was called
  Assert.NotNull(yourClass.registeredViewData);

  // Verify 'GetName' private method was invoked and
  // 'Name' was properly populated
  Assert.AreEqual("expected name", yourClass.registeredViewData.Name);
}

// Nested class for testing purposes only.
class ShuntedYourClass : public YourClass
{
  public ViewData registeredViewData;

  public override void Notify(ViewData vd)
  {
    this.registeredViewData = vd;
  }
}

This code now verifies that the Initialize method does indeed work properly and executes the Notify with the proper parameters.

Hope that helps!

Brandon