Home > Blockchain >  When Does It Make Sense to Mock an Exception Class?
When Does It Make Sense to Mock an Exception Class?

Time:04-08

I've noticed that when you upgrade Spring Boot to at least 2.5.11, it seems that any exceptions that you mock such as

@Mock
private MissingServletRequestParameterException missingServletRequestParameterException;

then try to actually use the mock in the following manner

when(missingServletRequestParameterException.getParameterName()).thenReturn("Name");
when(missingServletRequestParameterException.getParameterType()).thenReturn("Type");
logger.error("An error has occurred: ", missingServletRequestParameterException);

will throw a NullPointerException. The same piece of code above works fine up to Spring Boot 2.5.10.

However, given the fact that you could just create an Exception object, it doesn't seem that you would really need to mock Exception classes at all. But maybe there are cases that you would need to do just that?

I'm not an expert with using mocking frameworks, so it would be nice to fill in that knowledge gap.

CodePudding user response:

The purpose of mocking a class is so that you can remove any logic that the class has, and either replace it with your own logic, or eliminate it altogether. Therefore, you should only EVER mock classes that have some kind of logic. Mocking a class that's just got a bunch of fields, with getters and setters, is a waste of time.

Now, if your exception class has logic in it, then it's doing more than an exception class should. You've violated the single responsibility principle. Don't do that.

In short then, you should NEVER be mocking your exception classes. If you think you need to, then it's a sure sign you've done something wrong.

  • Related