简体   繁体   English

为什么RhinoMock不能通过该测试?

[英]Why does RhinoMock not fail this test?

I have a class that acts like this at the moment: 目前,我有一个这样的班级:

public class MyClass {

    public void Method1(){
        if (false) {
            Method2();
        }
    }

    public void Method2(){
        //do something here
    }
}

So Method2 is never called (my code looks a bit different but I have this if-clause that evaluates to false and therefore doesn't execute the Method2. Checked it by debugging to be sure). 因此,永远不会调用Method2(我的代码看起来有些不同,但是我有这个if子句,其结果为false,因此不执行Method2。请通过调试进行检查,以确保确定)。 I want to tell RhinoMocks that I expect Method2 to be called and the test to fail: 我想告诉RhinoMocks我希望Method2被调用并且测试失败:

MockRepository mock = new MockRepository();
MyClass presenter = mock.PartialMock<MyClass>();

Expect.Call(() => presenter.Method2()).IgnoreArguments();

mock.ReplayAll();
presenter.Method1();
mock.VerifyAll();

...but the test passes. ...但是测试通过了。

(The reason for the lambda expression in the Expect.Call is, that my actual Method2 has arguments) (在Expect.Call中使用lambda表达式的原因是,我的实际Method2具有参数)

My questions: 我的问题:

  • Is this the usual approach for testing in this scenario? 这是在这种情况下进行测试的常用方法吗? (I'm just starting with RhinoMocks and mocking-frameworks in general) (我只是从RhinoMocks和模拟框架开始)
  • Why does the test pass? 为什么测试通过?

As confirmed by Jakob's comments, PartialMock only mocks abstract/virtual methods, so your expectation isn't actually doing anything. 正如Jakob的评论所证实的, PartialMock仅模拟抽象/虚拟方法,因此您的期望实际上没有做任何事情。

Personally I don't generally mock out methods within the class I'm testing. 就我个人而言,我通常不会在正在测试的类中模拟方法。 I just mock out dependencies, and express those through interfaces instead of concrete classes, avoiding this problem to start with. 我只是模拟出依赖关系,并通过接口而不是具体的类来表达依赖关系,从而避免了这个问题的产生。

I think there is a lot of value in partially mocking out concrete classes. 我认为部分模拟具体的类有很多价值。 Say for example you have a couple private methods that get called within a class. 举例来说,您有几个在类中调用的私有方法。 You obviously would need to make them 'internal' before testing, but you would like to have a way to test this -- without making a new class (which isn't the right solution in a lot of cases). 您显然需要在测试之前将它们设置为“内部”,但是您希望有一种方法可以对此进行测试-无需创建新的类(在很多情况下,这不是正确的解决方案)。

To make this test fail you would just have the signature of Method 2 to: 要使此测试失败,您只需使用方法2的签名即可:

public virtual void Method2(){} 公共虚拟虚空Method2(){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM