Get return value of invoked method in UnitTest using Moq

Viewed 237

I'm using Moq to do unit testing. In the method I'm trying to unit test I'm trying to ensure that it doesn't throw an exception but I'd also like to get the return value of the method I'm unit testing to verify the result.

_myService.Invoking(x => x.TestMethod(request)).Should().NotThrow();

The above works. The test passes. However, I'd like to get the return value of TestMethod.

2 Answers

Well here's the thing, try to test what you WANT to get, not what you DON'T WANT:

Bad(making sure we DON'T get exception):

_myService.Invoking(x => x.TestMethod(request)).Should().NotThrow();

Good(making sure we get what we WANT):

var result = _myService.TestMethod(request);
// whatever asserts you want to perform on `result`
// e.g.
// Assert.IsNotNull(result);
// Assert.IsTrue(result.Count == 2);
// Assert.AreEqual(result[0],"Foo");
// etc.

If the method returns the value you expect it to return, it automatically means that the method has not thrown an exception.

On the other hand, if an exception was thrown, there would be no return value.

Related