Search code examples
c#unit-testingexceptionmoqxunit

Setup InnerException with Moq


I am trying to Setup() InnerException using Moq in my unit tests.

var exceptionMock = new Mock<Exception>();

exceptionMock.Setup(e => e.InnerException)
                .Returns(new Exception());

But I am getting this error:

System.NotSupportedException: 'Unsupported expression: e => e.InnerException
Non-overridable members (here: Exception.get_InnerException) may not be used in setup / verification expressions.'

I guess it is because InnerException is not a virtual property.

How to setup InnerException for any Exception using Moq in unit tests?


Solution

  • You do not need to use Moq for that behavior. Just create an Exception like this:

    var exception = new Exception("message", new Exception());