Answer To ‘Why Use A Dummy Exception?’

dummy exception

 

In yesterday’s post, I asked why it might be desirable to throw a dummy exception type in a unit test.

Thank you to everyone who sent in their answers. I liked Kishor Tiwari’s answer best. Well done, Kishor!

OK, let’s get into why a dummy exception type can be a good idea in a unit test. Here is yesterday’s unit test example again:

  [Theory]
  [InlineData("Client Input Error")]
  [InlineData("a different error message")]
  public async Task Given_UseCase_Throws_ClientInputException_When_Call_Register_Then_Return_400_BadRequest(string errorMsg)
  {
     var controller = SetupController(new DummyClientInputException(errorMsg));
     var result = await controller.Register(ApiRegoAdamAnt);
     VerifyBadRequestResult(result, errorMsg);
  }

The test verifies that class under test, the controller emits an HTTP 400-Bad Request response when it catches a ClientInputException. 

By design, ClientInputException is abstract, and we cannot, therefore, instantiate it directly:

  public abstract class ClientInputException : Exception
  {
     public ClientInputException(string message)
        : base(message)
     { }
  }

However, we could use one of ClientInputException’s many concrete child exceptions in the unit test instead:

  [Fact]
  public async Task Given_UseCase_Throws_ClientInputException_When_Call_Register_Then_Return_400_BadRequest()
  {
     var controller = SetupController(new MissingEmailAddress());
     var result = await controller.Register(ApiRegoAdamAnt);
     VerifyBadRequestResult(result, errorMsg);
  }

However, this has drawbacks:

  • The test has lost clarity. There is a disconnect between the test name how the unit is set up. We are meant to be testing for ClientInputExceptions—so why are we using a MissingEmailAddress exception? Is the test name wrong?—are we meant to be testing for MissingEmailAddress?? Ah, right, a MissingEmailAddress must be a ClientInputException. We are asking the reader of this unit test to make too many inferences. We should always aim to write our unit tests to be crystal-clear as to their purpose. On the other hand, DummyClientInputException does not suffer from the same problem. Its name clearly describes it as a ClientInputException. 
  • The test is more fragile. If MissingEmailAddress changes base exception type to ValidationException, say, this unit test will break. And it will break for reasons unrelated to what the test is verifying —that a ClientInputException, not a ValidationException, will generate a 400-Bad Request. 

So, dummy exceptions can be a good idea.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply