c# – Rhino Mocks Partial Mock

前端之家收集整理的这篇文章主要介绍了c# – Rhino Mocks Partial Mock前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从一些现有的类测试逻辑.由于它们非常复杂并且在生产中,因此不可能重新考虑目前的类别.

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

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

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

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

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

  1. using System;
  2. using MbUnit.Framework;
  3. using Rhino.Mocks;
  4.  
  5. namespace MMBusinessObjects.Tests
  6. {
  7. [TestFixture]
  8. public class PartialMockExampleFixture
  9. {
  10. [Test]
  11. public void Simple_Partial_Mock_Test()
  12. {
  13. const string param = "anything";
  14.  
  15. //setup mocks
  16. MockRepository mocks = new MockRepository();
  17.  
  18.  
  19. var mockTestClass = mocks.StrictMock<TestClass>();
  20.  
  21. //record beahvIoUr *** actualy call into the real method stub ***
  22. Expect.Call(mockTestClass.MethodToMock(param)).Return(true);
  23.  
  24. //never get to here
  25. mocks.ReplayAll();
  26.  
  27. //this is what i want to test
  28. Assert.IsTrue(mockTestClass.MethodIWantToTest(param));
  29.  
  30.  
  31. }
  32.  
  33. public class TestClass
  34. {
  35. public bool MethodToMock(string param)
  36. {
  37. //some logic that is very hard to mock
  38. throw new NotImplementedException();
  39. }
  40.  
  41. public bool MethodIWantToTest(string param)
  42. {
  43. //this method calls the
  44. if( MethodToMock(param) )
  45. {
  46. //some logic i want to test
  47. }
  48.  
  49. return true;
  50. }
  51. }
  52. }
  53. }

解决方法

MethodToMock不是虚拟的,因此无法模拟.您想要做的是使用部分模拟(我在类似于您的情况下完成它),但您想要模拟的方法必须是接口实现的一部分或标记为虚拟.否则,您无法使用Rhino.Mocks进行模拟.

猜你在找的C#相关文章