Tutorial 1
This tutorial introduces the basic annotation supports that implemented in Junit 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
Result
@BeforeClass – oneTimeSetUp
@Before – setUp
@Test – testEmptyCollection
@After – tearDown
@Before – setUp
@Test – testOneItemCollection
@After – tearDown
@AfterClass – oneTimeTearDown
In JUnit 4, we have to declare “@BeforeClass” and “@AfterClass” method as static method.
Tutorial 2
The “exception testing” means what exception throw from the unit test.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Result
Unit test marked success
Tutorial 3
The “Ignored” means whether it should ignore the unit test.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Result
unit test ignored
Tutorial 4
The “Time Test” means if an unit test takes longer than the specified number of milliseconds to run, the test will terminated and mark as fails.
import org.junit.*; /** * JUnit TimeOut Test * @author mkyong * */ public class JunitTest4 { @Test(timeout = 1000) public void infinity() { while (true); } }
Result
java.lang.Exception: test timed out after 1000 milliseconds
Tutorial 5
The “Suite Test” means bundle a few unit test and run it together.
The “@RunWith” and “@Suite” are use to run the suite test. The below class means both unit test “JunitTest1” and “JunitTest2” run together after JunitTest5 executed. All the declaration is define inside the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Result
@BeforeClass – oneTimeSetUp
@Before – setUp
@Test – testEmptyCollection
@After – tearDown
@Before – setUp
@Test – testOneItemCollection
@After – tearDown
@AfterClass – oneTimeTearDown
P.S Result is from JunitTest1 and JunitTest2 unit test
Tutorial6
The “Parameterized Test” means vary parameter value for unit test. The “@RunWith” and “@Parameter” is use to provide parameter value for unit test, @Parameters have to return List[], and the parameter will pass into class constructor as argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
Result
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 3
Parameterized Number is : 4
It has many limitations here; we have to follow the “JUnit” way to declare the parameter, and the parameter has to pass into constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is “List []”, data has been limited to String or a primitive value for testing.