Rhino模拟AAA期望违反异常



运行rhinomock测试方法时出错:测试方法TestProject1.UnitTest2.TestMethod1引发异常:Rhino.Mocks.Exceptions.ExpectionViolationException:ITestInterface.Method1(5);应为#1,实际为#0。

我的代码看起来像:-

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;
        }
    }
}

我的测试看起来像:-

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));
        }
    }
}

感谢您的帮助。

您希望ITestInterface.Method1被调用,但它从未被调用
在测试代码中根本不使用mockProxy——您只需创建它并创建自己的实例,但它们之间没有关系
您的TestClass不依赖于您想要模拟的任何接口,使用模拟的类似示例是:

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));
    }
}

我认为你应该阅读更多关于使用Rhino Mocks的信息,例如Rhino Mocks AAA Quick Start?

最新更新