Assertions:
Assertions in JUnit 5 Assertions are a set of methods present in Junit 5 Assert Class which is used in asserting various conditions in tests.
While using assertion, we are going to import this asserts class as static import, and then we will call its methods.
JUnit 5 Assertions
In Assert JUnit 5 we still have the lot of methods from JUnit 4 and few newer methods as well which follow Java 8 in implementation. You can do assertions on all primitive type, Objects and Array type.
With Java 8 support, the output message can be a supplier, allowing lazy evaluation.
Let’s see the available assertions that we can use:
JUnit 5 Assertions methods
- assertArrayEquals: It verifies the equality of arrays.
- assertEquals: If we need to assert two values, we can use assertEquals. It also supports diff between the two, and for that we need to pass an additional delta parameter.
- assertTrue: It is used to assert the true statement.
- assertFalse: It is used to assert the false statement. For both assert true and false, we can use boolean supplier provided by java8 instead of boolean condition.
- assertSame and assertNotSame: It is used to assert that the actual and expected refer to the same object and not same in assertNotSame case.
- assertNull and assertNotNull: it is used to assert null and non-null values.
7. fail: fail assertion fails the test case, used in case of test cases half cooked that means in development stage like in case of TDD (Test Driven Development) approach we can use it.
8. assertAll: assert all is used in case of grouping the assertions and their results are reported together.
9. assertNotEquals: Used to check non-equality of expected and actual values.
10. assertThrows: Used to assert the thrown exception
Let’s see all of these one by one
package com.slb.core.unittest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class AssertionsDemo {
@Test
public void whenAssertingEquality() {
String expected = "SLB";
String actual = "SLB";
Assertions.assertEquals(expected, actual);
}
@Test
public void whenAssertingNonEquality() {
String expected = "SLB";
String actual = "Simplified Learning Blog";
Assertions.assertNotEquals(expected, actual);
}
@Test
public void whenAssertingArraysEquality() {
char[] expected = {'J','A','V','A','8'};
char[] actual = "JAVA8".toCharArray();
assertArrayEquals(expected, actual);
}
@Test
public void whenAssertingNotSameObject() {
Object ram = new Object();
Object shyam = new Object();
assertNotSame(ram, shyam);
}
@Test
public void whenAssertingSameObject() {
Object ram = new Object();
Object rahul = ram;
assertSame(ram, rahul);
}
@Test
public void whenAssertingTrueConditions() {
assertTrue( 100 > 10);
}
@Test
public void whenAssertingFalseConditions() {
assertFalse( 5 > 6);
}
// @Test
// public void whenAssertingTriggersFail() {
// fail("Exception scenario");
// }
@Test
public void testAssertThat() {
assertAll( "asserting all", ( () -> assertTrue( 5 > 4) ), () -> assertFalse( 3 > 4) );
}
@Test
void whenAssertingException_thenThrown() {
Throwable exception = assertThrows(
ArithmeticException.class,
() -> {
throw new ArithmeticException("Exception message");
}
);
assertEquals("Exception message", exception.getMessage());
}
}
All of the above code is available at SLB GitHub
How to Utilize Assertions Effectively
When writing unit tests, it’s essential to utilize assertions correctly. Here are some tips for crafting effective assertions in JUnit 5:
- Be Specific
Make sure your assertions are specific and related to the behavior you are testing. Steer clear of making generalizations that may not apply in this particular instance. - Include Descriptive Messages
Include descriptive messages with your assertions to make it obvious what is being tested and why. Doing this can be especially useful when a test fails, as it helps identify the issue quickly. - Validate Positive and Negative Cases
It is essential to test both positive and negative cases for each behavior being tested, in order to guarantee that your code behaves as expected in all scenarios. Doing this will help guarantee that the code works as expected across all scenarios. - Minimize Assertion Clutter
Be mindful when including too many assertions in one test method. Doing so may make the test hard to read and comprehend, potentially making it more difficult to pinpoint why a failure occurred. - Select the Appropriate Assertion Type
Select the correct assertion type for testing a condition. For instance, assertEquals() can be used when comparing two objects for equality and assertNull() can be used when testing for null values.
Example 1: Test Cases Using JUnit 5 Assertions
Let’s take a look at some example test cases that use JUnit 5 assertions.
@Test
void testAddition() {
Calculator calculator = new Calculator();
int result = calculator.add(12, 3);
assertEquals(15, result, "Addition of two numbers should return the correct sum.");
}
In this above example, we are testing the addition of two numbers using the assertEquals() assertion method. The test passes if the result of the addition is equal to the expected value of 15, otherwise it will fail.
Example 2: Testing the Division of Two Numbers
@Test
void testDivision() {
Calculator calculator = new Calculator();
double result = calculator.divide(100, 2);
assertEquals(50, result);
}
In this example, we are testing the division of two numbers using the assertEquals() assertion method. If the result of the division equals 50 as expected, then our test passes.
Example 3: Testing for Null Values
@Test
void testNullValue() {
MyTestClass myTestClass = new MyTestClass ();
assertNull(myTestClass.getProperty(), "Property should be null.");
}
In this example, we are testing that a property in the MyTestClass object is null using the assertNull() assertion method. If the property is null, then our test passes.
Conclusion
Assertions in JUnit 5 are an integral component of writing successful unit tests in Java. By using specific and targeted assertions, providing descriptive messages, and testing both positive and negative cases alike, you can ensure your code behaves as expected under all circumstances. With a wide selection of assertion methods at your disposal, you have the flexibility to test various conditions and scenarios with confidence.
FAQ
What is the Difference Between JUnit 4 and JUnit 5?
JUnit 5 introduced many new features and improvements from its predecessor, such as support for Java 8 or later, parameterized tests, and enhanced extension capabilities.
What are some best practices for writing unit tests?
Some recommended practices when crafting unit tests include writing specific and targeted tests, using descriptive names for both tests and methods, testing both positive and negative cases, and efficiently using assertions.
How Can I Run JUnit Tests in My IDE?
Most IDEs provide support for running JUnit tests out-of-the-box. You usually right-click a test class or method and select either “Run” or “Run as JUnit test”.
What are some popular testing frameworks for Java?
Popular options include TestNG, Mockito and AssertJ.
How can I improve the performance of my unit tests?
You can boost performance by minimizing external resources like databases or network connections, using mocking frameworks to simulate dependencies, and running tests in parallel.
Previous Topic: JUnit 5