JUnit test tutorial with assert exception

This is my second article on JUnit test tutorial with assert exception. I have covered some test conditions based on assertions. Definitely it helps you.

JUnit test tutorial with assert exception

Let’s start following test conditions

Assertion is a tool to verify test conditions.

The org.junit.Assert package provides static overloaded methods to assert expected and actual values for all primitive types, objects, and array. You can add static import in the test class.

import static org.junit.Assert.*;

  • assertTrue(condition) or assertTrue(failure message, condition) – If the condition becomes false, the assertion fails and AssertionError is thrown.
  • assertFalse(condition) or assertFalse(failure message, condition) -If the condition becomes true, the assertion fails
  • assertNull: This checks whether the object is null, otherwise throws AssertionError if the argument is not null.
  • assertNotNull: This checks whether the argument is not null; otherwise, it throws AssertionError.
  • assertEquals(string message, object expected, object actual), or assertEquals(object expected, object actual), or assertEquals(primitive expected, primitive actual) – If objects are passed, then the equals() method is invoked.
  • assertSame(object expected, object actual): This supports only objects and checks the object reference using the == operator. If two different objects are passed, then AssertionError is thrown.
  • assertNotSame: This is just the opposite of assertSame. It fails when the two argument references are the same

Testing for exceptions

To test an error condition, exception handling feature is important . For example if a method calculateDivision(int a, int b), calculates arithmetic division of two numbers, then it should throw ArithmeticException when divisor is 0. If the method doesn’t throw an exception, the test should fail.

@Test(expected= ArithmeticException.class)

public void testCalculateDivision () {

Caulator. calculateDivision(9, 0);


Exception testing can be done in better way utilizing @Rule .

Testing for Timout

JUnit tests are automated to get quick feedback after a change in the code. If a test runs for a long time, it violates the quick feedback principle. JUnit provides a timeout value (in milliseconds) in the @Test annotation to make sure that if a test runs longer than the specified value, the test fails.

The following is an example of a timeout:


public void forEver() throws Exception {



Above JUnit test tutorial with assert exception are sufficient for initially start and understand about JUnit. Soon I will publish another third session article on JUnit.



Share This Post

Post Comment