Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to the deprecated ExpectedException.none() in JUnit 4.13

I am trying to use the @Rule annotation with ExpectedException

The ExceptedException.none() method to initialize a variable type of ExceptedException says it has been deprecated what are the alternatives to initialize an object of the ExceptedException. Example:

public ExpectedException expectedException = ExpectedException.none();

@Test
public void testThrownException() throws Exception {
    expectedException.expect(CustomException.class);
    expectedException.expectMessage("Exception Message");
    ...
}
like image 322
Prashant Kumar Singh Avatar asked Jun 13 '20 04:06

Prashant Kumar Singh


People also ask

Does expectedexception have to be null?

Also, this test does not actually require the exception message to not be null, as long as the right type of exception is thrown. This passes the test: If we want to test anything beyond that the exception type, we’re going to need a @Rule annotation and the ExpectedException class.

Do we need a catch for an Unchecked exception In JUnit?

And there’s no need for us to write a Catch for an unchecked exception: if the constructor throws an irrelevant exception, JUnit will report it in much the same manner our more verbose tests do. But… out IDE is giving us a warning that badDeposit is not actually used.

Can you use JUnit 5 and ArithmeticException in the same project?

But of course that causes ArithmeticException, which matches the class specified by the first parameter, so the test passes. To make it easier to change over to JUnit 5, the new version of the testing framework is structured in such a way that you can use both JUnit 5 and a previous version in the same project.

How to write a test to reject null In JUnit?

Write a test that requires the constructor should reject null in place of a proper Currency instance to pass, and give an exception message that is neither null nor an empty String. If you don’t know about assertThrows () in JUnit 5, and you don’t really like what’s available in JUnit 4, you might write a test like this:


1 Answers

Did you read the deprecation notice?

Deprecated. Since 4.13 Assert.assertThrows can be used to verify that your code throws a specific exception.

See this answer for an example:

like image 160
Joe Avatar answered Sep 26 '22 19:09

Joe