首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rhino Mocks部分模拟

Rhino Mocks部分模拟
EN

Stack Overflow用户
提问于 2010-05-04 19:41:29
回答 2查看 13.1K关注 0票数 7

我正在尝试测试一些现有类的逻辑。目前还不可能对这些类进行重构,因为它们非常复杂且处于生产阶段。

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

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

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

我是不是遗漏了什么,或者如果不重构类就不可能进行测试?

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

代码语言:javascript
复制
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;
            }
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-05-04 20:10:40

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

票数 15
EN

Stack Overflow用户

发布于 2010-05-04 19:52:29

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

代码语言:javascript
复制
 Expect.Call( delegate { mockTestClass.MethodToMock(param) } ).Return(true);

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

代码语言:javascript
复制
    [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();
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2764929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档