简体   繁体   English

预期对该模拟调用一次,但为0次

[英]Expected invocation on the mock once, but was 0 times

I need to define that in the method AddOrEdit triggered a different method Add. 我需要定义在方法AddOrEdit中触发了另一个方法Add。 The add method adds a new instance. add方法添加一个新实例。 But I catch the the error. 但是我发现了错误。 The Add method works in debug. Add方法可在调试中使用。 What am I doing wrong? 我究竟做错了什么?

var repository = new Mock<IRepository>();
var layer = new Layer(repository.Object);

// Arrange
var object1=new Object1();
var object2=new Object2();
repository.Setup(a => a.Add<Object1>(new Object1(){Name="Name"}));

// Act
layer.AddOrEdit(object1, object2);

// Assert
repository.Verify(a => a.Add<Object1>(new Object1(){Name="Name"}));

public void AddOrEdit(Object1 object1, Object2 object2))
{
    ......
    ......
    Add(object2.Name)
}
public void Add(string name)
{
     Repository.Add(new Object1(){Name="Name"});
}

Update: 更新:

I removed 我删除了

repository.Setup(a => a.Add<Object1>(new Object1(){Name="Name"}));

And override Equals 并覆盖等于

public override bool Equals(object obj)
{
    var item = obj as Object1;

    return item != null && this.Name.Equals(item.Name);
}

repository.Verify(a => a.Add<Object1>(new Object1(){Name="Name1"})); // Test Failed
repository.Verify(a => a.Add<Object1>(new Object1(){Name="Name"}));  // Test Success

Update2 Andy offered a better solution Update2 Andy提供了更好的解决方案

repository.Verify(a => a.Add(It.Is<Object1>(y => y.Name == "Name")));

I think in your Verify call you should use 我认为您应该在验证电话中使用

It.Is<Object1>(y => y.Name == "Name")

This should verify the call, and you won't need to override equals in your class just for testing purposes. 这将验证调用,并且您无需仅出于测试目的就重写类中的equals。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 预期在 Mock 上调用一次,但为 0 次 - Expected invocation on Mock once, but was 0 times 预期在模拟上调用一次,但被调用0次:没有配置任何设置? - Expected invocation on the mock once, but was 0 times: No setups configured? 预期在模拟上调用一次,但使用 Moq 为 0 次 - Expected invocation on the mock once, but was 0 times With Moq 在模拟上预期调用一次,但是是2次:m => m.SaveChanges(),UnitTest - Expected invocation on the mock once, but was 2 times: m => m.SaveChanges() , UnitTest MOQ 单元测试错误。 预期在模拟上调用一次,但为 0 次 - MOQ Unit testing error. Expected invocation on the mock once, but was 0 times 预期对模拟进行一次调用,但使用Func(T,TResult)进行了0次 - Expected invocation on the mock once, but was 0 times, with Func(T, TResult) 对模拟的预期调用恰好 1 次,但为 0 次 - Expected invocation on the mock exactly 1 times, but was 0 times Moq 异常:预期在模拟上调用一次,但为 0 次...... - .Net Core 3.1 with xUnit - Moq Exception: Expected invocation on the mock once, but was 0 times... - .Net Core 3.1 with xUnit 预期至少对模拟调用一次,但从未执行 - Expected invocation on the mock at least once, but was never performed 预期对模拟的调用恰好 5 次,但正确模拟为 0 次 arguments - Expected invocation on the mock exactly 5 times, but was 0 times with properly mocked arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM