使用 Moq 测试私有方法不起作用

发布于 2024-08-19 20:34:40 字数 1130 浏览 3 评论 0原文

我正在使用 Moq,而且我对它有点陌生。 我需要测试一个私有方法。

我有 2 个程序集:

CustomerTest.dll
CustomerBusiness.dll

所以 CustomerTest dll 有一个类如下:

[TestFixture]
public class CustomerTestFixture
{
    var customerMock=new Mock<ICustomer>()
    customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true);

   etc...
}

CustomerBusiness.dll 有

公共接口 ICustomer { 无效购买(); 我

public class Customer:ICustomer
{
    public void Buy()
    {
        etc...
    }

    protected virtual bool CanTestPrivateMethod()
    {
        return true;
    }

}

收到以下错误

System.ArgumentException : Member ICustomer.CannotTestMethod does not exist.
at Moq.Protected.ProtectedMock`1.ThrowIfMemberMissing(String memberName, MethodInfo method, PropertyInfo property)
at Moq.Protected.ProtectedMock`1.Setup(String methodOrPropertyName, Object[] args)

我还添加了 [ assembly:InternalsVisibleTo("CustomerTest.CustomerTestFixture") 但没有区别!

我做错了什么。我知道我的接口没有这样的方法。这就是我的方法必须是私有的。你能帮忙举个例子吗?

I am using Moq and I am sort of new to it.
I need to test a private method.

I have 2 assemblies:

CustomerTest.dll
CustomerBusiness.dll

So
CustomerTest dll has a class as follows:

[TestFixture]
public class CustomerTestFixture
{
    var customerMock=new Mock<ICustomer>()
    customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true);

   etc...
}

CustomerBusiness.dll has

public interface ICustomer
{
void Buy();
}

public class Customer:ICustomer
{
    public void Buy()
    {
        etc...
    }

    protected virtual bool CanTestPrivateMethod()
    {
        return true;
    }

}

I get the following error

System.ArgumentException : Member ICustomer.CannotTestMethod does not exist.
at Moq.Protected.ProtectedMock`1.ThrowIfMemberMissing(String memberName, MethodInfo method, PropertyInfo property)
at Moq.Protected.ProtectedMock`1.Setup(String methodOrPropertyName, Object[] args)

I have also added [assembly: InternalsVisibleTo("CustomerTest.CustomerTestFixture")
but with no difference!

What Am I doing wrong. I know my Interface has not such a method.That is the point as my method must be private. Can you help with an example?

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

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

发布评论

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

评论(1

沉睡月亮 2024-08-26 20:34:40

当您创建模拟对象时,它会实现要模拟的类型或接口的虚拟和抽象成员。

通过创建一个Mock,它实现了客户接口的单一方法。它不知道您在 Customer 类中添加的方法。如果您需要模拟该方法,则需要创建一个 Mock

When you create a mock object, it implements virtual and abstract members of the type or interface to be mocked.

By creating a Mock<ICustomer>, it implements the one method of the customer interface. It has no knowledge of the method you added in the Customer class. If you need to mock that method, you need to create a Mock<Customer>.

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