我需要在 AddOrEdit 方法中定义触发了不同的方法 Add。add 方法添加一个新实例。但我发现了错误。Add 方法在调试中有效。我究竟做错了什么?
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"});
}
更新:
我删除了
repository.Setup(a => a.Add<Object1>(new Object1(){Name="Name"}));
并覆盖 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提供了更好的解决方案
repository.Verify(a => a.Add(It.Is<Object1>(y => y.Name == "Name")));