0

Pretty new to Java and trying to practice writing unit tests. I have a few similar custom exceptions to the below and wondering what way I can write a test to cover this.

public class ExampleException extends RuntimeException{
    public ExampleException(String message, Throwable e) {
        super(message, e);
    }
}
hotspuds
  • 47
  • 1
  • 7
  • 4
    all you have there is a constructor, what is there to test? – Stultuske Feb 07 '22 at 12:33
  • 1
    the only member, the constructor, has 2 parameters - so I can think of tests for: 1) is it constructing an instance (no {other] Exception being thrown by constructor); 2) is the passed message being stored; 3) is the passed Throwable being stored; 4) *eventually* inheritance (some method(s) of super-class) – user16320675 Feb 07 '22 at 12:45
  • 1
    Have a look at this answer. It may help https://stackoverflow.com/questions/40268446/junit-5-how-to-assert-an-exception-is-thrown – DeltaRage Feb 07 '22 at 13:10

1 Answers1

1

Testing exceptions in JUnit 5 is done through Assertions.assertThrows. You give it an exception type and an action that should throw exceptions of this type. If it doesn't the assertion fails. If it does it returns the thrown exception, which allows you to perform more assertions on the exception itself.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20