I have a method that calls a service to retrieve an instance of an object, updates the instance then saves the instance back to the service (the code for this is below).
What I want to know is if there is a nice way in Moq to check the following:-
- That the instance that is being saved back to the service is a modified version of the original instance
- That the instance has been updated as desired
I know I can use It.Is<MyThing>(x => x.Name == newName)
to check for point 2 here. Doing this ignores point 1 though.
Is there a clean way to achieve this?
CLASS CODE:
public class MyClass
{
private readonly IThingService thingService;
public MyClass(IThingService thingService)
{
this.thingService = thingService;
}
public void SaveMyThing(MyThing myThing)
{
var existingThing = thingService.Get(myThing.Id);
existingThing.Name = myThing.Name;
thingService.Save(existingThing);
}
}
public class MyThing
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IThingService
{
MyThing Get(int id);
void Save(MyThing myThing);
}
TEST CODE:
[Test]
public void Save_NewName_UpdatedThingIsSavedToService()
{
// Arrange
var myThing = new MyThing {
Id = 42,
Name = "Thing1"
};
var thingFromService = new MyThing
{
Id = 42,
Name = "Thing2"
};
var thingService = new Mock<IThingService>();
thingService
.Setup(ts => ts.Get(myThing.Id))
.Returns(thingFromService);
thingService
.Setup(ts => ts.Save(**UPDATED-THING-FROM-SERVICE**))
.Verifiable();
var myClass = new MyClass(thingService.Object);
// Act
myClass.SaveMyThing(myThing);
// Assert
thingService.Verify();
}