JUnit 5 assertNotEquals() Example

Hey guys in this post, we will discuss the Junit5 assertNotEquals() method with easy to understand example




Read More:

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.

Screenshot-2022-07-24-at-6-31-36-PM

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.

Screenshot-2022-07-24-at-6-44-35-PM

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.

Screenshot-2022-07-24-at-6-45-36-PM

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.



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *