-
Notifications
You must be signed in to change notification settings - Fork 248
Log[Severity] Extension Methods Make Unit Testing Logging Behavior Difficult #611
Comments
@pranavkm Question: why are these extension methods instead methods on the main interface |
@ardalis you can check @PureKrome Right now the |
I was going to echo this. |
What is the recommended way to verify a particular Log method was hit?
|
That's the only way to do it. Don't get me wrong, it's a PITA but converting those extension methods to interface methods would be a disaster. |
Cheers! |
I can see the reasoning to keep ILogger simple; thanks! |
For anybody else who stumbles onto this: |
That's an interesting compromise @ardalis :) Nice! |
@ardalis thanks for the blog post!! extension methods aren't quite convincing, especially as it makes unit testing painful. At least Debug(string msg), Warn(string msg), Info(string msg), Error(string msg) and Error(Exception ex) could have been part of ILogger, as those are common methods that everybody expects to be part of any logging framework. |
Using extension methods rather than interface methods on ILogger makes it difficult to mock an ILogger effectively, which in turn makes unit testing logging behavior in classes that perform logging difficult.
Consider this controller code:
I want to write a unit test that confirms a warning message is logged when the exception is thrown. I can easily mock the service to throw the exception. But I can't mock the
_logger.LogWarning
call because it's an extension method:This code fails at runtime:
The text was updated successfully, but these errors were encountered: