【问题标题】:Can (or should) I mock methods on the object being tested other than the method being tested?除了正在测试的方法之外,我可以(或应该)模拟正在测试的对象上的方法吗?
【发布时间】:2008-11-19 10:33:48
【问题描述】:

我有这样的课:

public class ClassA
{
    public bool MethodA()
    {
      //do something complicated to test requiring a lot of setup
    }
    public bool MethodB()
    {
         if (MethodA())
             //do something
         else
             //do something else
         endif
    }
}

我对 MethodA 进行了测试并想测试 MethodB,但我要做的只是验证 MethodA 是否返回 true 是否发生了某些事情,如果 MethodA 返回 false 是否发生了其他事情。我可以用 Rhino Mocks 做到这一点吗?或者我是否必须设置我已经在 MethodA 测试中使用的所有相同模拟?

【问题讨论】:

    标签: unit-testing mocking rhino-mocks


    【解决方案1】:

    您可能必须从类中提取接口或使其抽象,我有理由相信 Rhino.Mocks 可以模拟类和接口。这意味着您应该能够执行以下操作:

    ClassA myClass = MockRepository.PartialMock(typeof(ClassA));
    
    Expect.Call(myClass.MethodA).Return( true );
    
    MockRepository.ReplayAll()
    Assert.AreEqual( false, myClass.MethodB() )
    MockRepository.VerifyAll()
    

    语法可能有点偏离,但应该允许 MethodB 独立于 MethodA 进行测试

    【讨论】:

    • 这可行,但前提是被部分模拟的类上的方法是虚拟的。谢谢,我知道这一定是可能的。
    【解决方案2】:

    很难说这在没有上下文的情况下是否可行,但一种解决方案可以将 MethodA() 提取到它自己的类中,这样您就可以让 MethodB() 在一个模拟对象上调用 MethodA() ,该对象将充当您的单元测试愿望。

    另一种可能性是在您的单元测试中继承 ClassA 并覆盖 MethodA() 以根据您的单元测试返回 true 或 false。

    //--- pseudo-code 
    public ClassAMethodAReturnTrue : public ClassA { 
      public bool MethodA() { return true; } 
    
      ...
    

    然后在您的测试中,您实例化 ClassAMethodAReturnTrue 而不是 ClassA。同样,您将编写 ClassAMethodAReturnFalse。

    【讨论】:

    • 所以基本上你说这是不可能的。我不想将方法移动到其他类或创建子类,所以我想我将不得不硬着头皮再次模拟 methodA 内部的调用。
    • 不,你可以在你的测试中继承 ClassA 来重新定义 MethodA。
    • 啊。好的,我现在明白了,对不起。是的,这将是另一种可行的方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2021-07-18
    • 2021-09-17
    • 1970-01-01
    • 2017-03-07
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多