如何断言/验证 Moq 受保护方法?
我有一个应该返回 true 的私有方法。我正在使用 Nunit 和 MOQ 所以我有如下:
[TestFixture]
public class CustomerTestFixture
{
var customerMock=new Mock<ICustomer>()
customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true);
// How do I assert it now since I cannot do
customerMock.Verify //Verify does not exists.
}
在谷歌上找不到任何告诉你如何测试它的东西。 如您所见,我可以为其进行设置,但无法断言。
我错过了显而易见的事情吗?多谢。
I have a private method that should return true.I m using Nunit and MOQ
So i have as follows:
[TestFixture]
public class CustomerTestFixture
{
var customerMock=new Mock<ICustomer>()
customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true);
// How do I assert it now since I cannot do
customerMock.Verify //Verify does not exists.
}
Could not find anything on google that tells you how to test it.
as you can see I can do a set up for it but cannot assert.
Am I missing the obvious? Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不想在模拟上测试方法。您想要在实际类的实例上测试该方法。在类上测试私有方法的方法是使用访问器。请注意,VS 将自动为您提供这些,或者您可以使用反射“自行推出”。对于内部方法,您还可以在 AssemblyInfo.cs 文件中将 InternalsVisibleTo 设置为您的测试项目。
当您模拟一个对象时,其目的是将该对象用作被测试的实际类的依赖项。因此,能够设置模拟对象以返回特定值就足够了。您正在使用依赖项的类上进行断言,而不是模拟类上。验证步骤确保您的被测类根据您建立的期望调用模拟对象上的方法。
You don't want to test a method on a mock. You want to test the method on a instance of the actual class. The way to test a private method on a class is to use an accessor. Note that VS will provide these for you automatically, or you can "roll your own" using reflection. For an internal method, you can also set InternalsVisibleTo to your test project in the AssemblyInfo.cs file.
When you mock an object, the intent is that that object is being used as a dependency for the actual class under test. Therefore, it's enough to be able to set up the mock object to return specific values. You're doing your assertions on the class that uses the dependency, not on the mock class. The verification step ensures that your class under test called the methods on the mock objects according to the expectations you've established.