加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Rhino Mocks Partial Mock

发布时间:2020-12-15 18:30:21 所属栏目:百科 来源:网络整理
导读:我试图从一些现有的类测试逻辑.由于它们非常复杂并且在生产中,因此不可能重新考虑目前的类别. 我想要做的是创建一个模拟对象并测试一个内部调用另一个非常难以模拟的方法的方法. 所以我想为次要方法调用设置一个行为. 但是当我设置方法的行为时,方法的代码被
我试图从一些现有的类测试逻辑.由于它们非常复杂并且在生产中,因此不可能重新考虑目前的类别.

我想要做的是创建一个模拟对象并测试一个内部调用另一个非常难以模拟的方法的方法.

所以我想为次要方法调用设置一个行为.

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

我是否遗漏了某些东西,或者这是不可能在没有重新分类的情况下进行测试?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读