Rhino Mocks部分模拟

7
我试图测试一些现有类的逻辑。由于这些类非常复杂且已在生产中使用,目前无法重构这些类。
我的目标是创建一个模拟对象并测试一个内部调用另一个非常难以模拟的方法的方法。
因此,我只想为次要方法调用设置行为。
但是当我设置方法的行为时,方法的代码被调用并失败了。
我是否漏掉了什么或者说没有进行重构就不可能进行测试?
我尝试了所有不同类型的模拟(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;
            }
        }
    }
}
2个回答

15

MethodToMock方法不是虚拟的,因此无法进行模拟。您想要做的是使用部分模拟(我已经在类似您情况下的案例中这样做过),但是您想要模拟的方法必须是接口实现的一部分或者被标记为虚拟方法。否则,您无法使用Rhino.Mocks进行模拟。


只是要补充一点,您不能从接口生成部分模拟。被模拟的方法必须确实标记为虚拟的。 - krystan honour

1

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

 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 ); 调用类的MethodToMock方法,该方法将抛出NotImplementedException异常。 - dotnet crazy kid
1
MethodToMock 应该是虚函数。 - dvjanm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接