Rhino Mocks 部分模拟

2024-01-03

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

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

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

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

我是否遗漏了一些东西,或者如果不重构课程就无法进行测试?

我已经尝试了所有不同的模拟类型(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;
            }
        }
    }
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rhino Mocks 部分模拟 的相关文章

随机推荐