Search code examples
c#unit-testingmockingrhino-mocks

Rhino mock AAA ExpectationViolationException


Getting Error while running rhinomock test method : Test method TestProject1.UnitTest2.TestMethod1 threw exception: Rhino.Mocks.Exceptions.ExpectationViolationException: ITestInterface.Method1(5); Expected #1, Actual #0.

My code looks like:-

namespace ClassLibrary1
{
    public interface ITestInterface
    {
        bool Method1(int x);

        int Method(int a);
    }

    internal class TestClass : ITestInterface
    {

        public bool Method1(int x)
        {
            return true;
        }

        public int Method(int a)
        {
            return a;
        }
    }
}

And my test looks something like:-

using ClassLibrary1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace TestProject1
{
    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void TestMethod1()
        {
            ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();

            TestClass tc = new TestClass();
            bool result = tc.Method1(5);           

            Assert.IsTrue(result);


            mockProxy.AssertWasCalled(x => x.Method1(5));

        }
    }
}

Any help appreciated.


Solution

  • You expect ITestInterface.Method1 to be called, but it never does.
    You don't use your mockProxy at all in the test code - you just create it and you create your own instance, but there's no relation between the two of them.
    Your TestClass is not dependant upon any interface that you want to mock, similar example that does use the mock would be:

    internal class TestClass
    {
        private ITestInterface testInterface;
    
        public TestClass(ITestInterface testInterface)
        { 
           this.testInterface = testInterface;
        }
    
        public bool Method1(int x)
        {
            testInterface.Method1(x);
            return true;
        }
    
    }
    
    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void TestMethod1()
        {
            ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();
    
            TestClass tc = new TestClass(mockProxy);
            bool result = tc.Method1(5);           
    
            Assert.IsTrue(result);
    
    
            mockProxy.AssertWasCalled(x => x.Method1(5));
        }
    }
    

    I think you should read more about using Rhino Mocks, e.g. Rhino Mocks AAA Quick Start?