Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

junit
java

What are the assertions in JUnit?

lfrah Dar

When we develop a test case, we have one expected output and one actual output. Assertion helps us compare these outputs and evaluate whether a given test case is pass or fail.

We can use assertion in JUnit after we import it into the file:

import static org.junit.Assert.*;

All assertion methods are available in JUnit assert class.

Assert Methods

The JUnit provides all assert methods by default.

Let’s take a look at few assert methods:

  • assertEquals: Evaluates whether the expected and actual outputs of the test case are equal.
  • assertArrayEquals: Evaluates whether the expected and actual arrays are equal.
  • assertNull: Evaluates if the object is Null.
  • asserNottNull: Evaluates if object is not Null.
  • assertSame: Evaluates if two objects are pointing to the same object.
  • assertNotSame: Evaluates if two objects are not pointing to the same object.
  • assertTrue: Evaluates if the condition is true.
  • assertFalse: Evaluates if the condition is false.

Code

Let’s take a look at a few assertion examples.

import static org.junit.Assert.*;  
import org.junit.*;                

public class assertTest { 

  //assertEqual compares two strings 
    @Test
    public void assertEquslTest() {
        String stractual = "This is the testcase1";
        assertEquals("This is the testcase1", stractual);
    }
    
    //assertArrayEqualsTest compares two array
    @Test
    public void assertArrayEqualsTest() {
        int expected[] = {1,2,3,4,5};
        int actual[]   = {1,2,3,4,5};
        assertArrayEquals(expected, actual);
    }
    
    //assertFalse checks value is false
    @Test
	public void assertFalseTest() {
		boolean value = false;
		assertFalse(value);
	}

    //assertTrue checks value is true
    @Test
	public void assertTrueTest() {
		boolean value = true;
		assertTrue(value);
	}
}

OK (4 tests) shows that all 4 test cases are passing.

If one of these test cases fails, the output will be Tests run: 4, Failures: 1.

RELATED TAGS

junit
java

CONTRIBUTOR

lfrah Dar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring