Search code examples
nunitrhino-mocks

Testing mocked objects rhino mocks


I am new to RhinoMocks, and I am trying to write a test as shown I have classes like these

public class A
{
    public void methodA(){}
}
public class B
{
    public void methodB(A a)
    {
      a.methodA();
    }
}

And i am trying to test it like this

A a = MockRepository.GenerateMock<A>();
public void ShouldTest()
{
    B b = new B();
    b.methodB(a);
    a.AssertWasCalled(x=>x.methodA());
    a.VerifyAllExpectations();
}

But it is giving the error as shown: System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call.

How do I test methodB then?? Can someone help??


Solution

  • Rhino mock creates proxy class when you call MockRepository.Generate *** method. This means that it extends your type. If you don't declare any abstraction you cannot make any derivation which is essential in any mocking framework.

    You can do two things

    1. Create an interface (better design)
    2. Make the member virtual (this will allow RhinoMocks to derive from your type and create a proxy for the virtual member

    Sample code

    public interface IA { void methodA();}
    public class A:IA{public void methodA() { }}
    public class B
    {
        public void methodB(IA a)
        {
            a.methodA();
        }
    }
    
    [TestFixture]
    public class Bar
    {
        [Test]
        public void BarTest()
        {
            //Arrange
            var repo = MockRepository.GenerateMock<IA>();
    
            //Act
            B b = new B();
            b.methodB(repo);
    
            //Assert
            repo.AssertWasCalled(a => a.methodA());
            repo.VerifyAllExpectations();
        }
    }