Place your test classes here: /src/test/<pkg_name>/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
int a=4, b=5, c;
c = a + b;
assertEquals(9, c); // This test passes
assertEquals(10, c); //Test fails
}
}
public class ExampleUnitTest {
...
}
The test class, you can create several test classes and place them inside the test package.
@Test
public void addition_isCorrect() {
...
}
The test method, several test methods can be created inside a test class.
Notice the annotation @Test
.
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
There are several other useful annotations like @Before
, @After
etc. This page would be a good place to start.
assertEquals(9, c); // This test passes
assertEquals(10, c); //Test fails
These methods are member of the Assert
class. Some other useful methods are assertFalse()
, assertNotNull()
, assertTrue
etc. Here's an elaborate Explanation.
Annotation Information for JUnit Test:
@Test: The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.
@Before: When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with @Before
causes that method to be run before the Test method.
@After: If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After
causes that method to be run after the Test method. All @After
methods are guaranteed to run even if a Before or Test method throws an exception