JUnit Basics

Unit tests are written to ensure that small units of code function as intended. When it comes to Unit tests, the higher your code coverage, the higher your confidence when refactoring and/or extending code functions and features. Unit tests play an incredibly important role when it comes to sustaining and maintaining code.

JUnit is a simple, yet powerful unit test framework for Java. JUnit enables you to construct test cases quickly and assert expected results.

To illustrate its, simplicity, here is a sample unit test:

package com.cdimasci.test;

// statically import JUnit assertion methods
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        // Run once before any method in this class.
    }

    @Before
    public void setUp() throws Exception {
        // Runs once before each method annotated with @Test
    }

    @Test
    public void testSomething() {
        // The Sample Test case
        fail("Not yet implemented");
    }

    @Test
    public void testAnotherThing() {
        // Another Sample Test case
        Me me = new Me();
        assertEquals("Carmine", me.getFirstName());
    }

    @After
    public void tearDown() throws Exception {
        // Runs once after each method annotated with @Test.
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        // Run once after all test cases are run
    }

}

Typical uses for the above annotations

  • @BeforeClass – Typically used for for expensive test setup. Is run once before any test case is run
  • @Before – Typically used when test cases require similar resources. We can write the code once, yet it will run before each and every test case in the test class.
  • @Test – Your test case
  • @After – Commonly used to clean up resources that were allocated in the @Before method. Run after each and every test case. It is guaranteed to run, even if exceptions occurs in @Before or @Test
  • @AfterClass – Commonly used to clean up test resources allocated in @BeforeClass. This is run after all test cases run. It is guaranteed to run even if exceptions are thrown in @BeforeClass

Test Suites group a set of test classes

@RunWith(Suite.class)
@SuiteClasses({ MyTest.class, SomeOtherTest.class })
public class AllTests {

}

There are many ways to run JUnit tests and test suites e.g. programatically, via the command line, via an integrated IDE plugin, etc.
Below is an example of using the Eclipse Junit ‘view’ to run the sample JUnit test above. Notice that the failure message is displayed by JUnit.

eclipse-junit

Thanks!

You may also like...

1 Response

  1. September 3, 2013

    […] Junit Basics (cdimascio.wordpress.com) […]

Leave a Reply