Skip to main content

Learn your testing framework

Testing frameworks can offer a lot in terms of features, assertions and utility functions. It is always better to learn the maximum about your testing framework, that will help you to use the appropriate features and will certainly make your unit tests more readable, elegant and reliable.

Example

In the following example we manually check if an exception was thrown when invoking the increaseCount() method.

If you still check for exceptions like that with JUnit the you certainly may not know that JUnit offer a simpler way to validate for exceptions.


@Test
void increaseCount_Throws_MaximumCapacityReachedException_When_Max_Val_Reached(){

counter.setCount(Counter.MAX_CAPACITY);

boolean thrownException = false;

try {

counter.increaseCount();

} catch(MaximumCapacityReachedException e ){
thrownException = true;
}

}

Improvement

Like we have seen in a previous example, you can use the assertThrows assertion to check for exceptions. Our test case is now a one liner clean statement that checks for MinimumCapacityReachedException exception.

@Test
void decreaseCount_Throws_MinimumCapacityReachedException_When_Count_Is_Zero(){

assertThrows(MinimumCapacityReachedException.class,()->counter.decreaseCount());

}