1. Annotation Type Test
The Test annotation tells JUnit that the public void methos 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. Any exceptions thrown by the test will be reported by JUnit as failure. If no expectations are thrown, the test is assumed to have succeeded.
A simple test looks like this:
public class Example{
@Test
public void method(){
org.junit.Assert.assertTrue(new ArrayList().isEmpty());
}
}
Example in Eclipse IDE:
1. Open your Eclipse IDE.
2. Add a new class to the test project
3. If needed please import the Junit library to your currect project decency libraries.
4. Write a class named SimpleTest and extend junit.framework.TestCase (actually if you Junit4, you don't need extend junit.framework.TestCase)
5. Write a test method and asserting desired result. You can use annotation "@Test" to declare this method is test method.
Figure: Example for JUnit @Test annotation |
Right click within the test method area and choose "Run As - JUnit Test"
Test annotation with optional parameters:
The Test annotation supports two optional parameters:
a. expected
b. timeout
1.1 Test annotation with 'expected' optional parameter:
The first, expected, declared that a test method should throws an exception. If it doesn't throw an exception or it it throws a different exception that the one declared, the test fails. For example, the following test succeeds.
Example:
@Test(expected=IndexOutOFBoundsException.class)
public void outOfBounds(){
new ArrayList<Object>().get(1);
}
Example in Eclipse:
Crate a following class in Eclipse IDE.
import org.junit.*;
public class JunitTest2
{
@Test(expected = ArithmeticException.class)
public void divisionWithException(){
int i = 1/0;
}
}
Right click within the test method area and choose "Run As - Junit Test"
Figure: Test annotation with expected parameter. |
In the above example, the divisionWithException() method will throw an ArithmeticException exception, since this is an expected excpetion, so the unit test will pass.
1.2 Test annotation with 'timeout' optional parameter:
The second optional parameter, timeout, causes a test to fail if it takes longer than a specified amount of clock time (measured in milliseconds). The following test fails.
Example:
Create a following class in Eclipse IDE and name it as JUnitTest3
import org.junit.Test;
public class JUnitTest3
{
@Test(timeout=1000)
public void infinity()
{
while(true)
}
}
Right click within the test method area and choose "Run As - JUnit Test"
Figure: Test annotation with timeout parameter |
In the above example, the infinity() method will throw an time out exception, and the test will fail.
No comments:
Post a Comment