JUnit Maven Dependency
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Basic annotations @Before, @After, @BeforeClass, @AfterClass
Executed before every @Test method
@Before
public void setUp() {
}
Executed after every @Test method
@After
public void tearDown() {
}
Executed once before all @Test methods
@BeforeClass
public void setUpBeforeClass() {
}
Executed once after all @Test methods
@AfterClass
public void tearDownAfterClass() {
}
Test methods annotation. @Test
@Test
public void someTest() {
}
For time limited (in milliseconds) tests use @Test(timeout = 5000)
For testing of exceptions use @Test(expected = SomeSpecificException.class)
Parameterized tests
The class should be declared with @RunWith(Parameterized.class) annotation.
@RunWith(Parameterized.class)
public class SomeTestClassName {
}
You should provide the method with @Parameters annotation that returns collection of arrays. Every test will be executed with each array as with a parameters set
@Parameters
public static Collection<Object[]> params() {
return someParams;
}
You have to have the constructor method with arguments corresponding to Object[] mentioned above.
private SomeParamType1 param1;
private SomeParamType2 param2;
private SomeParamType3 param3;
...
public SomeTestClassName( SomeParamType1 param1, SomeParamType2 param2, SomeParamType3 param3) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
...
}
JUnit Assertions
AssertTrue("Some message if not true", true);
AssertEquals("Some message if Fail", expectedResult, ActualResult);
JUnit Test suites
You can use Suite classes as containers for your tests. @Suite.SuiteClasses defines classes that are included into the suite and the order of execution.
@RunWith(Suite.class)
@Suite.SuiteClasses({SomeTestClassName1.class, SomeTestClassName2.class,
SomeTestClassName3.class, ...})
public class SomeTestSuiteName {
}
Leave the suite class empty
Need more?
You may also find these posts interesting: