Assertions in JUnit

Assertions are what JUnit is all about. The code you are testing is doing something. Your assertions will test that after running the software under test with a certain set of inputs, you will have a specified output.

assertArrayEquals()

The assertArrayEquals() method will test whether two arrays are equal to each other i.e. they have same number of elements and all the elements in the array are equal to each other.
Also they must be in same order.

    @Test
    public void testAssertArrayEquals(){
		Employee employee = new Employee();
		String[] expectedArray = {"Puneet", "Sahil"};
		String[] resultArray =  employee.getAllNames();
		assertArrayEquals(expectedArray, resultArray);
    }

assertEquals()

The assertEquals() method checks that two primitives/Objects are equal.

	@Test
    public void testAssertEquals(){
        assertEquals(15, 10 + 5);
    }

assertTrue()

The assertTrue() method checks that the condition is true.

	@Test
    public void testAssertTrue(){
        assertTrue(10 > 4);
    }

assertFalse()

The assertFalse() method checks that the condition is false.

	@Test
    public void testAssertFalse(){
        assertFalse(10 == 4);
    }

assertNull()

The assertNull() method checks that an object is null.

	@Test
    public void testAssertNull(){
		String name = null;
        assertNull(name);
    }

assertNotNull()

The assertNotNull() method checks that an object is not null.

	@Test
    public void testAssertNotNull(){
		String name = "Puneet";
		assertNotNull(name);
    }

assertSame()

The assertSame() method checks if two object references point to the same object or not.

	@Test
    public void testAssertSame(){
		String name = "Puneet", newname = "Puneet";
		assertSame(name,newname);
    }

assertNotSame()

The assertNotSame() method checks that both variables refer to different objects.

	@Test
    public void testAssertNotSame(){
		String name = "Puneet", newname = "Sahil";
		assertNotSame(name,newname);
    }
You can download the source code of this example here.


,

No comments yet.

Leave a Reply