Reputation: 13
I need to define that in the method AddOrEdit triggered a different method Add. The add method adds a new instance. But I catch the the error. The Add method works in debug. 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
repository.Verify(a => a.Add(It.Is<Object1>(y => y.Name == "Name")));
Upvotes: 1
Views: 6384
Reputation: 8562
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.
Upvotes: 3