Reputation: 29674
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
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
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