Rhino Mocks 验证从公共方法调用私有方法

发布于 2024-09-06 07:06:37 字数 468 浏览 8 评论 0原文

我一直在试图弄清楚这个问题,如何测试在我正在测试的类中使用 rhino 模拟调用私有方法。所以我的课会是这样的。

Public class Foo
{
    public bool DoSomething()
    {
       if(somevalue)
       {
          //DoSomething;
       }
       else
       {
          ReportFailure("Failure");
       }
    }

    private void ReportFailure(string message)
    {
        //DoSomeStuff;
    }
}

所以我的单元测试是在类 Foo 和方法 DoSomething() 上进行的,我想使用 rhino 模拟检查并确保如果某个值为 false,则将某个消息传递给 ReportFailure。

I have been trying to figure this one out, how do i test that a private method is called with rhino mocks with in the class that I am testing. So my class would be something like this.

Public class Foo
{
    public bool DoSomething()
    {
       if(somevalue)
       {
          //DoSomething;
       }
       else
       {
          ReportFailure("Failure");
       }
    }

    private void ReportFailure(string message)
    {
        //DoSomeStuff;
    }
}

So my unit test is on class Foo and method DoSomething() I want to check and make sure that a certain message is passed to ReportFailure if somevalue is false, using rhino mocks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

身边 2024-09-13 07:06:37

可能有一种方法可以做到这一点,但在大多数情况下您不想这样做。您的单元测试不应依赖于隐藏的实现或代码。当您测试类时,将它们视为黑盒,您只能更改输入并测试输出。

如果您正在测试私有方法的执行,那么您很可能会过于深入地研究给定类的实现,并且您很难在不破坏测试的情况下更改您的实现。

There probably is a way to do this, but in most circumstances you don't want to do this. Your unit tests shouldn't depend on hidden implementations or code. Treat your classes as black boxes when you test them, where you only have access to changing the input and testing the output.

If you are testing private method execution, you are very likely diving too far into the implementation of a given class, and you're making it difficult to change your implementation down the road without breaking tests.

最美不过初阳 2024-09-13 07:06:37

我同意 mjd79 的答案,但是如果您愿意验证 ReportFailure 是否被调用,那么您可以将该方法的保护级别更改为 Internal,并设置 InternalsVisibleTo程序集上的 code> 属性,以便您的单元测试可以访问它。

更好的方法可能是模拟 ReportFailure 访问的任何资源,并验证是否调用了该模拟上的某些公共方法。

I agree with mjd79's answer, however if you're married to the idea of verifying that ReportFailure was called then you could change the protection level of the method to Internal, and set the InternalsVisibleTo attribute on your assembly so that it allows your unit tests to access it.

A better approach might be to mock whatever resource ReportFailure accesses, and verify that some public method on that mock is invoked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文