Mock code in ASP.NET

Simon Leung
Simon Leung used Ask the Experts™
Can anyone explain what the attached code mean ?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

There you are testing that: Having an "AudioBookApiController" that receives an "AudioService", when you call the "Get" method on the AudioBookApiController object (apiController), it returns an AudioBook instance.

To do so: On the test you seem to be testing just the AudioBookApiController, not the service, so you create a Mock of the service (audioServiceMock) and then you configure the apiController instance with that mock (during the construction of the AudioBookApiController).

You also tell what will audioServiceMock return when "GetById" is called, --> it must return the variable audioBook.

Finally, you tell the apiController to Get the audioBook related with a Guid and you check (Assert.Equal) that the audioBook returned is the expected.


#1 audioServiceMock.Setup(x => x.GetById(It.IsAny<Guid>())).Returns(audioBook);

Does it initialize the audioServiceMock with audioBook ?

#2 var apiController = new AudioBookApiController(audioServiceMock.Object);
Does it return the audioBook object ?

#1 configures audioServiceMock so that when GetById is called with any Guid it returns the object audioBook

#2 creates a new instance of AudioBookApiController and tells it to use the audioService Mock

When you call apiController.Get(Guid.NewGuid()) it returns the audioBook object. - probably, inside, it calls audioServiceMock.GetById and then (#1 question enters in scene)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial