How-to articles, tricks, and solutions about JUNIT

How do I test a class that has private methods, fields or inner classes?

To test a class that has private methods, fields, or inner classes, you can do the following:

How to assert that a certain exception is thrown in JUnit tests?

To assert that a certain exception is thrown in a JUnit test, you can use the @Test annotation's expected attribute. Here's an example:

How to get the path of src/test/resources directory in JUnit?

In JUnit, you can use the getClass().getClassLoader().getResource("").getPath() method to get the path of the src/test/resources directory.

How to mock a final class with mockito

To mock a final class with Mockito, you can use the PowerMockito library.

How to run test methods in specific order in JUnit4?

In JUnit 4, you can use the @FixMethodOrder annotation to specify the order in which test methods should be executed.

How to test that no exception is thrown?

To test that no exception is thrown in a Java method, you can use the assertDoesNotThrow method from the org.junit.jupiter.api.Assertions class (part of the JUnit 5 library).

How to verify that a specific method was not called using Mockito?

To verify that a specific method was not called using Mockito, you can use the verifyZeroInteractions method.

JUnit 5: How to assert an exception is thrown?

To read a text file in Java, you can use the BufferedReader class from the java.io package.

Mockito : how to verify method was called on an object created within a method?

To verify that a method was called on an object created within a method using Mockito, you can use the Mockito.verify() method and pass it the object that you want to verify, as well as the method that you want to verify was called.

Mockito How to mock and assert a thrown exception?

To mock and assert a thrown exception in Mockito, you can use the doThrow() method and the verify() method.

Testing Private method using mockito

It is generally considered bad practice to test private methods, as they are an implementation detail that should not be exposed to the outside world.