Skip to content

Create a junit test suite

SWP-Comp-Ch3ck3r edited this page Apr 26, 2013 · 3 revisions

This is a small example of how to create a JUnit Test Suite in Eclipse.

A JUnit Test Suite contains as many tests as you like. Of course you are free to create several test suites per component.

Location of JUnit Test Suites

All JUnit Test Suites of your component have to be placed inside <your component folder>/test (e.g. code/ast/test). TestSuite files have to match *Test.java. Other files are ignored when the JUnit Tests are run.

Make sure to create your Tests inside of unique package names - same like all java classes.

Creating a JUnit Test

In eclipse click on new and select JUnit test case. Select JUnit version 4 your test directory as Source Folder.

If you want to auto generate test stubs you can select the class under test and then click on next to select the methods.

new junit test

Click on finish

Special methods:

JUnit has four special methods inside your test class.

setUpBeforeClass

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

This method is called once before the tests inside this test case are executed.

tearDownAfterClass

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

This method is called once after all the test inside this test case have been executed.

setUp

@Before
public void setUp() throws Exception {
}

This method is called once before every test inside this test case.

tearDown

@After
public void tearDown() throws Exception {
}

This method is called once after every test inside this test case.

Tests

Every method inside the test case annotated with @Test is executed as a test inside your test suite. E.g.:

@Test
public void test() {
    fail("Not yet implemented");
}

Standard JUnit Operations

Exception

Whenever an exception is thrown within a test that is not catched by yourself the test will fail.

The fail method

When you call fail("message here") your test will fail.

The Assertions

JUnit has a lot of assertion methods. Assertions will succeed when the given actualValue and expectedValue equal. Otherwise it will fail. JUnit has different Assertion method. Some examples:

assertSame(expected, actual);
assertEquals(expected, actual);
assertTrue(condition);
...

Private Access

If you need to access private methods or private fields of classes to check if your test failed, you can use the privilegedAccessor (PA) for that.

String somePrivateString = (String) PA.getValue(someObject, "thePrivateFieldName");
PA.invokeMethod(someObject, "myPrivateMethod", methodArguments);

Executing your test

To execute your test in eclipse, just hit run or run as JUnit Test. This will open a new View where you will see the result of your tests.

run junit test