Let's say I have a simple class called MyRequestHandler, and it has a method called ProcessRequest that simply takes a request object, maps it to a return object and returns that object. (This is obviously a very simple example of a much more complex method/test that I'm working on).
public class MyRequestHandler { private IMapper _mapper; public MyRequestHandler(IMapper maper) { _mapper = mapper; } public MyReturnObject ProcessRequest(MyRequestObject requestObject) { MyReturnObject returnObject = _mapper.Map<MyReturnObject>(requestObject); return returnObject; } } Now for unit testing (using Xunit), I want to test the ProcessRequest method, but obviously want to Moq the Map method, as such:
MyRequestObject requestObject = new RequestObject() { RequestInt = 1, RequestString = "Hello" }; MyReturnObject returnObject = new MyReturnObject() { MyInt = 1, MyString = "Hello" }; Mock<IMapper> mockMapper = new Mock<IMapper>(); mockMapper.Setup(m => m.Map<MyRequestObject>(requestObject)).Returns(returnObject); MyRequestHandler requestHandler = new MyRequestHandler(mockMapper.Object); MyReturnObject response = requestHandler.ProcessRequest(requestObject); Assert.Equal(returnObject.MyInt, response.MyInt); Assert.Equal(returnObject.MyString, response.MyString); The problem here is that Moq returns (and I guess it should be obvious that it is) a reference to returnObject, so my Asserts will always pass, even if my method were to change a value prior to returning the object. Now I could instantiate a new MyReturnObject in the Moq Setup/Return and compare the MyInt and MyString by the values I give to the new one, but what if it's a really complex object with 20 properties and lists of objects? Maybe I want to use AutoFixture to create the object being returned and use DeepEqual to compare them? Is this even possible? Am I looking at this wrong, or do I have to do some type of cloning in the Setup/Return to make this work?