Rhino Mocks 验证从公共方法调用私有方法
我一直在试图弄清楚这个问题,如何测试在我正在测试的类中使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能有一种方法可以做到这一点,但在大多数情况下您不想这样做。您的单元测试不应依赖于隐藏的实现或代码。当您测试类时,将它们视为黑盒,您只能更改输入并测试输出。
如果您正在测试私有方法的执行,那么您很可能会过于深入地研究给定类的实现,并且您很难在不破坏测试的情况下更改您的实现。
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.
我同意 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 theInternalsVisibleTo
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.