[英]Moq.MockException: Expected invocation on the mock exactly 1 times, but was 0 times: x => x.Init()
I have this method which verify if a method is called.我有这个方法来验证是否调用了一个方法。 I am using xUnit and MOQ in C#.
我在 C# 中使用 xUnit 和 MOQ。
[Fact]
public void VerifyIfInitCalled()
{
// Arrange
var mock = new Mock<ICal>();
var cal = new Cal(mock.Object);
// Act
cal.Init();
// Assert
mock.Verify(x => x.Init(), Times.Exactly(1));
}
and for my Cal class对于我的 Cal class
public class Cal : ICal
{
private ICal _cal;
public Cal(ICal cal)
{
_cal = cal;
}
public void Init()
{
Console.WriteLine("Init called"); ;
}
}
But, I run the unit test, it fails with error Moq.MockException: Expected invocation on the mock exactly 1 times, but was 0 times: x => x.Init()
although I have called the Init()
method.但是,我运行单元测试,它失败并出现错误
Moq.MockException: Expected invocation on the mock exactly 1 times, but was 0 times: x => x.Init()
尽管我调用了Init()
方法。
Your need to modify your Init()
to get your assert right您需要修改您的
Init()
以使您的断言正确
public void Init()
{
_cal.Init();
Console.WriteLine("Init called"); ;
}
and your interface ICal
need to have an Init()
member.并且您的接口
ICal
需要有一个Init()
成员。
But clearly you have a conception problem you are implementing ICal
and passing it into the class constructor.!.但显然你有一个概念问题,你正在实现
ICal
并将其传递给 class 构造函数。!
UPDATE更新
A unit test is specific to an implementation so your test method need to test the Cal
class.单元测试特定于实现,因此您的测试方法需要测试
Cal
class。
If your class call an other service and you need to mock and setup a method call to get specific result you will use moq
如果您的 class 调用其他服务并且您需要模拟并设置方法调用以获得特定结果,您将使用
moq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.