Hey guys in this post, we will discuss the Junit5 assertNotEquals()
method with easy to understand example
Read More:
- Check the Complete JUnit 5 Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Spring Boot JdbcTemplate Tutorials
- Check the Complete Spring Boot and Data JPA Tutorials
- Check the Complete Spring MVC Tutorials
- Check the Complete JSP Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
Overview
JUnit5 provides the assertNotEquals()
method, it asserts that the expected and actual values are not equal. There are many overloaded assertNotEquals()
methods available. Below is just a sample screenshot for your reference.
Example
Consider the following method for adding two numbers
package in.bushansirgur.main;
public class MyUtils {
public int add(int a, int b) {
return a + b;
}
}
JUnit5 Success Test Case
Now we want to write a JUnit5 test case for the above method, we can use the assertNotEquals()
method to check the expected and actual values are not equal.
package in.bushansirgur.main;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class MyUtilsTest {
@Test
void testAdd() {
MyUtils myUtils = new MyUtils();
assertEquals(7, myUtils.add(2, 4), () -> "2+4 should not be equal to 7");
}
}
When we run the test case, we should see a green bar indicating that the test case passed.
JUnit5 Failure Test Case
Now if anyone changes the implementation/logic then the test case should fail. Let’s change the method implementation with the following code –
package in.bushansirgur.main;
public class MyUtils {
public int add(int a, int b) {
return a + b + 1;
}
}
Now when we run the test case, we should see a red bar indicating that the test case failed.
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.