6

I want to test some code:

public ViewModel FillClientCreateViewModel(ViewModel model){
    model.Phone = new Phone { Name = "Test"};

    model.Phone = _entityInitializer.FillViewModel(model.Phone);
}

I also want to setup FillViewModel to return the same object as I give to it.

My test:

     entityInitMock.Setup(x => x.FillViewModel(It.IsAny<PhoneViewModel>())).Returns(It.IsAny<PhoneViewModel>());

 var result = TestedInstance.FillClientCreateViewModel(CreateViewModel);

 result.Phone.Name.ShouldBe("Test");

But in this case my test fell - because result.Phone.Name was cleaned by my mock.

How can I setup mock to just give me the same object which i give to it.

Ivan Korytin
  • 1,832
  • 1
  • 27
  • 41

1 Answers1

18
entityInitMock.Setup(x => x.FillViewModel(It.IsAny<PhoneViewModel>()))
    .Returns((PhoneViewModel m) => m);

The Moq QuickStart is a great reference for similar questions.

Johann
  • 4,107
  • 3
  • 40
  • 39
TrueWill
  • 25,132
  • 10
  • 101
  • 150
  • how do you make that work in ReturnsAsync ? I get "Cannot convert lambda expression to type ___ because it is not a delegate type". – johni Apr 22 '17 at 14:53
  • @johni See http://stackoverflow.com/questions/31527394/moq-returnsasync-with-parameters and http://stackoverflow.com/questions/21253523/setup-async-task-callback-in-moq-framework – TrueWill Apr 24 '17 at 13:40
  • Good answer. Such nuances in TDD scenarios are important to cover to get all the nuts and bolts in place for detailed TDD. Thanks. – Tore Aurstad Oct 11 '18 at 09:06