Liam
Liam

Reputation: 29674

Moq rethrow error passed into Setup

so I've got an error handling class that uses the interface:

public interface IEventLogger
  {
    void WriteError(Exception ex, string message);
  }

So I'm mocking this up with Moq for unit testing. This method would normally just log the error into the event viewer but for my unit test I want it to rethrow the exception passed into the method, i.e. I want the unit test to fail if an error is passed into this mocked class. Any ideas how I can do this?

I got this far:

 var moqIEventLogger = new Mock<IEventLogger>();
 moqIEventLogger.Setup(s => s.WriteError(It.IsAny<Exception>(), 
                                           It.IsAny<string>()));

But I wasn't sure how to access the original exception, if it's possible at all??

Upvotes: 1

Views: 294

Answers (2)

Nitin Agrawal
Nitin Agrawal

Reputation: 1361

Add this in ur setup (modified)

    moqIEventLogger.Setup(s => s.WriteError(It.IsAny<Exception>(), 
                                       It.IsAny<string>()))
                  .Callback<Exception ex, string s>(p =>
                  {
                         throw ex;
                  });

Assuming u hv class ClassA with method MyMethod where u ur calling WriteError method Your Assert should look like:

 Assert.Throws<Exception>(ClassA.MyMethod );

Upvotes: -1

Rafal
Rafal

Reputation: 12619

If you want it to only fail then use Throws method like:

moqIEventLogger
            .Setup(s => s.WriteError(It.IsAny<Exception>(),It.IsAny<string>()))
            .Throws<InvalidOperationException>();

If you want it to throw given as argument exception try:

moqIEventLogger
            .Setup(s => s.WriteError(It.IsAny<Exception>(),It.IsAny<string>()))
            .Callback((Exception ex, string s) => { throw ex; });

Upvotes: 5

Related Questions