1

I have a method on an interface:

string GetUserDetails(string whatever);

I want to mock this with MOQ, so that it returns whatever the method returns i.e user details - something like:

_mock.Setup( theObject => theObject.GetUserDetails( It.IsAny<string>( ) ) )
   .Returns( [object return by GetUserDetails method] ) ;

Any ideas?

arghtype
  • 4,376
  • 11
  • 45
  • 60
mayank gupta
  • 341
  • 1
  • 4
  • 16
  • You can do what's called a partial mock and use the concrete implementation of this method, but surely you're better off just mocking the return value? Instead set up your method to return some arbitrary string as your example suggests. The point of mocking is to isolate the code under test from its dependencies. – benjrb Oct 24 '17 at 15:58
  • yeah i understood your point, but we need to actually use the actual dataset returning from DB (from repository) instead of creating our own mock data to implement the Unit test cases. s – mayank gupta Oct 24 '17 at 16:08
  • You're not writing a unit test in that case, you need to write an integration test. Moq is not what you need in this scenario. You do not want to go any further down this route, use partial mocking here at your own peril. I'd suggest maybe reading up on the test pyramid and the difference between unit testing and integration testing. – benjrb Oct 24 '17 at 16:18
  • yes ! I think I need to talk to my tech lead on this .. Thank You ! – mayank gupta Oct 24 '17 at 16:24
  • No worries and great idea, I hope it proves useful for you – benjrb Oct 24 '17 at 16:28
  • yes discussion with you is quite useful, Actually the requirement is to write unit test cases using actual data not mock data.. – mayank gupta Oct 24 '17 at 17:29

1 Answers1

1

For situation described in question, you need to use partial mocking. In Moq there are two different ways to achieve it:

  1. Specifying CallBase on construction: var mock = new Mock<MyClass> { CallBase = true }; . In this case by default call on this object methods will execute real method implementation if any.

  2. Specifying CallBase for some specific method: mock.Setup(m => m.MyMethod()).CallBase();

See also When mocking a class with Moq, how can I CallBase for just specific methods?

arghtype
  • 4,376
  • 11
  • 45
  • 60
  • Thanks for your reply, but dont you think your both statements are same, this object methods will execute real method implementation if any. && If you want to call base method only for some specific method. – mayank gupta Oct 26 '17 at 18:00
  • @mayankgupta I've paraphrased the answer, these two are different approaches – arghtype Oct 26 '17 at 18:34