ASP.NET Core Test code

Simon Leung
Simon Leung used Ask the Experts™
on
What does the line below perform ?

audioServiceMock.Setup(x => x.Update(It.IsAny<Guid>(), It.Is<AudioBook>(ab => ab == audioBook))).Returns(audioBook)
TestCode02.png
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
It configures the mock so when the Update method is called with any Guid and a component of type "AudioBook" it will return the audioBook variable

Commented:
fcnatra is mostly right.  This line configures the mock so that when the Update method is called with any Guid and an AudioBook type which matches the condition; parameter ab equals variable audioBook, that it returns the audioBook variable.

In reality, though, your mock should be setup so that it accepts any parameter(s) of the specified type and returns a known result; e.g. -
audioServiceMock.Setup(x => x.Update(It.IsAny<Guid>(), It.IsAny<AudioBook>())).Returns(audioBook)

Open in new window

You verify that the parameters handled by the method are the parameters that you passed to the method (which in your attachment you already do on line 139).

-saige-

Author

Commented:
so, audioServiceMock.Setup(x => x.Update(It.IsAny<Guid>(), It.Is<AudioBook>(ab => ab == audioBook))).Returns(audioBook);

can be written as
audioServiceMock.Setup(x => x.Update(It.IsAny<Guid>(), It.IsAny<AudioBook>())).Returns(audioBook)

correct ?

will the audioServiceMock be setup with audioBook if for the code below, as parameter ab of audioServiceMock should already be setup with ab == audioBook, correct ?
     audioServiceMock.Setup(x => x.Update(It.IsAny<Guid>(), It.Is<AudioBook>(ab => ab == audioBook)))

Thx again.

Commented:
The way it is written now... It.Is<AudioBook>(ab => ab == audioBook) it returns the audioBook object when Update is called with any Guid and an the AudioBook object audioBook.

The way @it_saige proposes It.IsAny<AudioBook>() it returns the audioBook object when Update is called with any Guid and any object of type AudioBook.

Depending on what you want to test, you must use the first or the second option. The name of the test says: Update_AudioBookPassed_ReturnedProperAudioBook.... what does that mean?

- WhenUpdate_GivenAudioBookPassed_ThenSameAudioBookIsReturned ?
- WhenUpdate_GivenAnyAudioBook_ThenAudioBookAssociatedWithGuidIsReturned ?

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