如何断言/验证 Moq 受保护方法?

发布于 2024-08-19 17:46:09 字数 446 浏览 3 评论 0原文

我有一个应该返回 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 技术交流群。

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

发布评论

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

评论(1

空‖城人不在 2024-08-26 17:46:09

您不想在模拟上测试方法。您想要在实际类的实例上测试该方法。在类上测试私有方法的方法是使用访问器。请注意,VS 将自动为您提供这些,或者您可以使用反射“自行推出”。对于内部方法,您还可以在 AssemblyInfo.cs 文件中将 InternalsVisibleTo 设置为您的测试项目。

[TextFixture]
public class CustomerTestFixture
{
   var customer = new Customer();
   var accessor = new Customer_Accessor( new PrivateObject( customer ) );

   Assert.IsTrue( accessor.CanTestPrivateMethod() );

}

当您模拟一个对象时,其目的是将该对象用作被测试的实际类的依赖项。因此,能够设置模拟对象以返回特定值就足够了。您正在使用依赖项的类上进行断言,而不是模拟类上。验证步骤确保您的被测类根据您建立的期望调用模拟对象上的方法。

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.

[TextFixture]
public class CustomerTestFixture
{
   var customer = new Customer();
   var accessor = new Customer_Accessor( new PrivateObject( customer ) );

   Assert.IsTrue( accessor.CanTestPrivateMethod() );

}

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.

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