Search code examples
c#moqxunit

Is there a way to test if an exception is raised and caught in a xUnit test


I have a try-catch block that has the following structure that I need to unit test. I tried to verify if the logger called the LogError method but that as been proving to be quite difficult so I was wondering if there is a way to see if an exception is raised and caught instead?

try
{
  bool messageProcessed = ProcessMessage(sbMessage);
  if (!messageProcessed)
  {
    throw new Exception();
  }
}
catch (Exception ex)
{
  _logger.LogError("Message could not be processed");
}

Solution

  • No, there is no easy way to check if an exception is thrown and caught, and even if there where, it would likely be quite fragile, since exceptions are usually considered an internal implementation detail.

    The correct way should be to check if a log message has been written, if that is the requirement. If you inject the logger this should be fairly easy, if you are using a logging framework that suggest using a static constructor for the logger, it is possible to support optional injection, for example:

    public class MyClass{
    private static readonly ILogger DefaultLogger = CreateStaticLogger();
    private ILogger _logger;
    public MyClass() :this(DefaultLogger){}
    public MyClass(ILogger logger) => _logger = logger;
    

    Once you can inject your logger you can either use a regular class to mock it, or use a mocking framework. Either way you should be able to verify that the LogError-method is called. If you still have issues I would suggest posting a new question with your attempt.

    You might also consider if your class should let the outside world know about exceptions, other than logging? Should exceptions be re-thrown? Should an event be raised if there is some failure? Maybe a counter?