【问题标题】:Rhino Mocks Partial Mock犀牛模拟部分模拟
【发布时间】:2011-02-15 10:25:46
【问题描述】:

我正在尝试测试一些现有类的逻辑。目前无法重构这些类,因为它们非常复杂并且正在生产中。

我想做的是创建一个模拟对象并测试一个内部调用另一个很难模拟的方法的方法。

所以我只想为辅助方法调用设置一个行为。

但是当我为方法设置行为时,方法的代码被调用并失败。

我是否遗漏了什么,或者如果不重构类就无法测试?

我已经尝试了所有不同的模拟类型(Strick、Stub、Dynamic、Partial 等),但当我尝试设置行为时,它们最终都会调用该方法。

using System;
using MbUnit.Framework;
using Rhino.Mocks;

namespace MMBusinessObjects.Tests
{
    [TestFixture]
    public class PartialMockExampleFixture
    {
        [Test]
        public void Simple_Partial_Mock_Test()
        {
            const string param = "anything";

            //setup mocks
            MockRepository mocks = new MockRepository();


            var mockTestClass = mocks.StrictMock<TestClass>();

            //record beahviour *** actualy call into the real method stub ***
            Expect.Call(mockTestClass.MethodToMock(param)).Return(true);

            //never get to here
            mocks.ReplayAll();

            //this is what i want to test
            Assert.IsTrue(mockTestClass.MethodIWantToTest(param));


        }

        public class TestClass
        {
            public bool MethodToMock(string param)
            {
                //some logic that is very hard to mock
                throw new NotImplementedException();
            }

            public bool MethodIWantToTest(string param)
            {
                //this method calls the 
                if( MethodToMock(param) )
                {
                    //some logic i want to test
                }

                return true;
            }
        }
    }
}

【问题讨论】:

    标签: c# unit-testing tdd mocking rhino-mocks


    【解决方案1】:

    MethodToMock 不是虚拟的,因此不能被模拟。您想要做的事情可以通过部分模拟(我已经在与您的情况类似的情况下完成),但是您要模拟的方法必须是接口实现的一部分或标记为虚拟。否则,您无法使用 Rhino.Mocks 模拟它。

    【讨论】:

    • 只是补充一点,您不能从界面生成部分模拟。被模拟的方法必须确实标记为虚拟的。
    【解决方案2】:

    我建议在被测类中不要模拟方法,但您的情况可能是独特的,因为您目前无法重构该类以使其更易于测试。您可以尝试显式地创建一个委托,以防止在设置调用时调用该方法。

     Expect.Call( delegate { mockTestClass.MethodToMock(param) } ).Return(true);
    

    或者,切换到使用 AAA 语法,省略不推荐使用的结构。

        [Test]
        public void Simple_Partial_Mock_Test()
        {
            const string param = "anything";
    
            var mockTestClass = MockRepository.GenerateMock<TestClass>();
    
            mockTestClass.Expect( m => m.MethodToMock(param) ).Return( true );
    
            //this is what i want to test
            Assert.IsTrue(mockTestClass.MethodIWantToTest(param));
    
            mockTestClass.VerifyAllExpectations();
        }
    

    【讨论】:

    • 感谢您的帮助,我尝试了您所说的,但在这个简单的示例中,它仍然在 mockTestClass.Expect( m => m.MethodToMock(param) ).Return( true ) 行抛出异常;调用将抛出 NotImplementedException 的类 MethodToMock。
    • MethodToMock 应该是虚拟的
    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 2011-11-12
    • 2010-10-29
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多