JUnit

Java - Testing

Articles
Videos

mockito
powermock

mixture

This page is now completely in my other system.

@Ignore
@Before // The annotated method will be run before each each test method
@After // The annotated method will be run after each test method
@BeforeClass // The annotated method will be run before each test class
@AfterClass // The annotated method will be run after each test class
@Test(expected=NullPointerException.class)
@Test(timeout=10)

assertArrayEquals(expectedOutput, actualOutput)
assertEquals(expectedValue, actualValue)
assertTrue(boolean)
assertFalse(boolean)
assertNull

How can we create a JUnit test case inside Eclipse?

Lets assume that we have a class name App, by convention, we should create a class named AppTest.

  1. Right click on the main "test" folder.
  2. Select "New -> Other"
  3. In the "type to filter" box, type JUnit
  4. Click on "JUnit Test Case"
  5. Click Next
  6. Provide a name (AppTest) in the Name field
  7. Click Finish

How can we run a JUnit test case using Eclipse?

  1. Right click anywhere in the test file
  2. Select "Run As -> JUnit Test"

How can we create a JUnit test suite inside Eclipse?

  1. Right click on the main test folder
  2. Select "New -> Other"
  3. In the "type to filter", type JUnit
  4. Click on "JUnit Test Suite"
  5. Click Next
  6. Provide a name in the Name field
  7. Select existing test cases that you would like to be included in this test suite
  8. Click Finish

What is the purpose of the @Test annotation?

The @Test annotation indicate that the method is a "test" method.

What is the convention for naming a test method?

The name of the test method should start with "test" followed by the name of the method under test.

What is the signature of each test method?

The signature of each test method should start with public void.

What are the assert methods offered by JUnit?

  1. assertEquals(expectedValue, actualValue)
  2. assertTrue(boolean)
  3. assertFalse(boolean)
  4. assertArrayEquals(expectedOutput, actualOutput)
  5. assertNull

What is the purpose of the @Ignore annotation?

The @Ignore annotation is used to ignore a particular test because we haven't got time to implement or fix the test right now. We should avoid using this @Ignore annotation as much as possible, or we should have a limit on it somehow.

What is the purpose of the @Before annotation?

The @Before annotation is used to define a method that is automatically run before each test method.

@Before
public void before() {
  helper = new StringHelper()
}

What is the purpose of the @After annotation?

The @After annotation is used to defined a method that is automatically run after each test method.

@After
public void after() {
  helper = null;
}

What is the purpose of the @BeforeClass annotation?

The @BeforeClass annotation is used to define a method that is automatically run before each test class.

@BeforeClass
public static void beforeClass() {
}

What is the purpose of the @AfterClass annotation?

The @AfterClass annotation is used to defined a method that is automatically run after each test class.

@afterClass
public static void afterClass() {
}

What is the definition of success in JUnit?

Success is the absence of failure.

How can we programmatically add test cases to a test suite?

TestSuite suite = new TestSuite()
suite.addTest(new MoneyTest(“testMoneyEquals”));
suite.addTest(new MoneyTest(“testSimpleAdd”));
TestResult result = suite.run()

What is a test case and what is a test suite?

I NEED TO COME BACK TO THIS.

How should we organize your tests?

Unit tests should not be organized into suites unless it is necessary (for example, these set of tests should only run on Windows, and that set of tests should only run on Linux). If we need to organize unit tests in suites, perhaps we can put tests for Windows into a directory, or append 'Windows' to the name of the test classes, and create an ant task that run all matching tests (using wild card or regular expression matching), or we can use annotation

For each Java package in your application, define a TestSuite class that contains all the tests for that package. Define similar TestSuite classes that create higher-level and lower-level test suites in other packages and sub-packages of the application. Make sure your build process includes the compilation of all tests. By creating a TestSuite in each Java package, at various levels of packaging, you can run a TestSuite at any level.

How can we determine the version of JUnit?

import junit.runner.Version
System.out.println("Version: " + Version.id());

How can we run JUnit tests from the command line?

java org.junit.runner.JUnitCore TestClass1 [...other test classes...]

How can we run JUnit tests from the command line using the textual test runner?

java junit.textui.TestRunner TestClass1 [...other test classes...]

How can we run JUnit tests from the command line using the graphical test runner?

java junit.swingui.TestRunner TestClass1 [...other test classes...]

How can we run JUnit tests from inside a Java program?

org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);

How can we make our JUnit4 test classes runnable with a TestRunner designed to work with earlier versions of JUnit?

If we need to make our JUnit4 test classes runnable with a TestRunner designed to work with earlier versions of JUnit, declare a static method 'suite' that returns a test:

public static junit.framework.Test.suite() {
    return new JUnit4TestAdapter(Example.class);
}

How can we test for exception?

Use the expected attribute of the @Test annotation:

@Test(expected=NullPointerException.class)
public void testArraysSortWithNullCondition() {
  int[] numbers = null;
  Arrays.sort(numbers);
}

How can we test for performance?

@Test(timeout=10)
public void testArraysSortPerformance() {
  for (int i=0; i < 1000000; i++) {
    int[] numbers = {i, i - 1, i + 1};
    Arrays.sort(numbers);
  }
}

Code Samples:

package com.quantros.qsupport.homepage;

import mockit.Mocked;
import mockit.NonStrictExpectations;

import org.junit.Assert;
import org.junit.Test;

import com.quantros.qsupport.homepage.dao.HomepageDAO;

public class HomepageServletTest {

    @Mocked final HomepageDAO mockHomepageDAO = new HomepageDAO();

    @Test
    public void deriveInformationFromURI() throws Exception {

        new NonStrictExpectations() {
            {
                mockHomepageDAO.getEntitiesId(withMatch("AH|ah")); result="701313";
                mockHomepageDAO.getEntitiesId(withPrefix("CHP")); result = "704323";
            }};

        HomepageServlet o = new HomepageServlet();
        o.deriveInformationFromURI("/AH/");
        Assert.assertEquals(o.abbreviation, "AH");
        Assert.assertTrue(o.isHomePage);

        o.deriveInformationFromURI("/AH/index.jsp");
        Assert.assertEquals(o.abbreviation, "AH");

        /*
         *  Given /AH/old_index.jsp, the expected behavior is
         *  isHomePage should be false and abbreviation should be empty.
         */
        o.deriveInformationFromURI("/AH/old_index.jsp");
        Assert.assertEquals(o.abbreviation, "");
        Assert.assertFalse(o.isHomePage);

        /*
         * If the request includes a dot, and it is not index.jsp,
         * then it is not requesting the home page.
         */
        o.deriveInformationFromURI("/AH/somefile.jsp");
        Assert.assertEquals(o.abbreviation, "");
        Assert.assertFalse(o.isHomePage);

        /*
         * If the request includes a dot, and it is not index.jsp,
         * then it is not requesting the home page.
         */
        o.deriveInformationFromURI("/AH/index.css");
        Assert.assertEquals(o.abbreviation, "");
        Assert.assertFalse(o.isHomePage);

        /*
         * If the request includes a dot, and it is not index.jsp,
         * then it is not requesting the home page.
         */
        o.deriveInformationFromURI("/AH");
        Assert.assertEquals(o.abbreviation, "AH");
        Assert.assertTrue(o.isHomePage);

        o.deriveInformationFromURI("AH");
        Assert.assertEquals(o.abbreviation, "AH");
        Assert.assertTrue(o.isHomePage);

        /*
         * If the given URL is mixed case, we should still be able
         * to determine the ENTITIESID.  The logic for redirecting
         * is outside of the method being tested.
         */
        o.deriveInformationFromURI("ah");
        Assert.assertTrue(o.isHomePage);

        o.deriveInformationFromURI("/CHP/STELZ/");
        Assert.assertEquals(o.abbreviation, "CHP/STELZ");
        Assert.assertTrue(o.isHomePage);
    }
}

Why do we sometimes have to specify the third parameter for the assertEquals method?

The third parameter specifies the precision. This is useful when the method being tested returns a float or double, because calculation that results in a float or double are not very precise.

assertEquals(25.5, courseInstance.calculateMathAverage(), 0.01);

In the above code, if courseInstance.calculateMathAverage() returns a values that are within 0.01 difference from 25.5, the test would be ok (pass).

What are the assertion methods available with JUnit?

  1. assertTrue
  2. assertFalse
  3. assertEquals(expected, actual)

What packages do we need to import for JUnit?

import static org.junit.Assert.*;
import org.junit.Test;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License