使用 Moq 测试私有方法不起作用
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您创建模拟对象时,它会实现要模拟的类型或接口的虚拟和抽象成员。
通过创建一个
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 aMock<Customer>
.