0
0
JUnittesting~5 mins

assertNotEquals in JUnit

Choose your learning style9 modes available
Introduction

We use assertNotEquals to check that two values are different. It helps us make sure our program does not produce unwanted equal results.

When you want to confirm a function does not return a specific wrong value.
When testing that two objects or variables are not the same after an operation.
When verifying that a change in input causes a change in output.
When ensuring that a method does not mistakenly produce duplicate results.
When checking that a value has been updated and is no longer equal to the old value.
Syntax
JUnit
assertNotEquals(expected, actual);
assertNotEquals(String message, expected, actual);

expected is the value you do NOT want actual to be equal to.

You can add a message to explain the test if it fails.

Examples
This checks that the sum of 2 and 2 is NOT 5.
JUnit
assertNotEquals(5, calculateSum(2, 2));
This checks that the greeting is not "hello" and shows a message if it fails.
JUnit
assertNotEquals("Values should differ", "hello", getGreeting());
Sample Program

This test checks that newValue is not equal to oldValue. Since 15 is not 10, the test will pass.

JUnit
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;

public class SampleTest {

    @Test
    public void testNotEquals() {
        int oldValue = 10;
        int newValue = 15;
        assertNotEquals(oldValue, newValue);
    }
}
OutputSuccess
Important Notes

If the two values are equal, the test will fail and show an error.

Use assertNotEquals to catch unexpected equal results early.

Summary

assertNotEquals checks that two values are different.

It helps catch errors where values should not match.

You can add a message to explain the test failure.