Search code examples
c#unit-testingrhino-mocks

How to test a service function has required steps to run?


I have a service function which has required steps to run. I have many tries with Rhino Mocks but with no luck. I can't make it pass the test.

So the question will be what's the best way to test this? Is code refactoring needed?

Any help is appreciated. Thanks a lot.

public class Service : IService
{
    public void Initialize()
    {
        Function1();
        Function1();
        Function1();
    }

    public void Function1() {}
    public void Function2() {}
    public void Function3() {}

}

public interface IService
{
    void Initialize();
    void Function1();
    void Function2();
    void Function3();
}

[Test]
public void Test1
{
    var mockService = MockRepository.GenerateMock<OfficePrinterService>();

    mockService.Initialize();

    // Test will Error Here.
    // No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call
    mockService.AssertWasCalled(x=>x.Function1());
    mockService.AssertWasCalled(x=>x.Function2());
    mockService.AssertWasCalled(x=>x.Function3());
}

[Test]
public void Test2
{
    var mockService = MockRepository.GenerateMock<IOfficePrinterService>();

    mockService.Initialize();

    // Test will Error Here.
    // Rhino.Mocks.Exceptions.ExpectationViolationException : IService.Function1(); Expected #1, Actual #0.
    mockService.AssertWasCalled(x=>x.Function1());
    mockService.AssertWasCalled(x=>x.Function2());
    mockService.AssertWasCalled(x=>x.Function3());
}

Solution

  • You cannot setup expectations on your tested object, which is Service. It is not a mock. It is system under test. You should assert observable behavior of your Function methods call instead, without any mocking (as in - what Service consumer expects to happen when he calls Initialize? What calls it makes internally is irrelevant - your consumer doesn't need to know that, he's interested in final result).