c# - Rhino 模拟 AAA ExpectationViolationException

标签 c# unit-testing mocking rhino-mocks

运行 rhinomock 测试方法时出现错误:测试方法 TestProject1.UnitTest2.TestMethod1 引发异常: Rhino.Mocks.Exceptions.ExpectationViolationException: 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 不依赖于您想要模拟的任何接口(interface),使用模拟的类似示例是:

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?

关于c# - Rhino 模拟 AAA ExpectationViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9494609/

相关文章:

c# - 如何在关闭父表单之前加载子表单而不关闭它们

c# - 如何在客户端将 Json 数据设置为 camelCase once

c# - 字段是可序列化类型的成员,但属于不可序列化类型

c# - 无法访问通过 docker 在 Postman 的 80 端口上运行的 API

java - 使用 Mockito 测试委托(delegate)方法

Python assert_call_with,有通配符吗?

python - 如何测试我是否正确调用了 pickle.dump()?

java - 将 Mockito 与 PowerMock 一起使用时初始化异常错误

ruby - JRuby 和 Test::Unit 的 assert_raise

c# - 如何在 VS2010 的测试结果窗口中查看单元测试的输出?