gradle:
1 2 3 4 5 |
apply plugin: 'java' dependencies { testCompile 'junit:junit:4.12' } |
maven:
1 2 3 4 5 |
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> |
Expected Exceptions Test
1 2 3 4 |
@Test(expected = UnsupportedOperationException.class) public void reverseList() { list.getReverseList(); } |
@RunWith
BlockJUnit4ClassRunner – default junit runner
SpringJUnit4ClassRunner allows you to use dependency injection in test classes or to create transactional test methods.
MockitoJUnitRunner for automatic mock initialization.
Suite
Parameterized
Parameters class
1 2 3 4 5 6 7 8 9 |
@RunWith(value = Parameterized.class) public class ParametersTest { // ... @Parameters public static Collection<Object[]> data() { @Test //will be run Collection.size times public void testData(){ } |
JUnit 5 – @ExtendWith
1 |
@RunWith(SpringJUnit4ClassRunner.class) |
replace with
1 |
@ExtendWith(SpringExtension.class) |
@Rule
1 |
@Rule public ExpectedException exception = ExpectedException.none(); |
1 |
@Rule public TemporaryFolder folder = new TemporaryFolder(); |
or your custom rule:
1 |
public class MyCustomRule implements TestRule { |
hamcrest – how to test lists
1 2 3 4 5 |
<dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> |
1 2 |
// https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest testCompile group: 'org.hamcrest', name: 'java-hamcrest', version: '2.0.0.0' |
check if single element is in a collection
1 2 |
assertThat(Lists.newArrayList("a", "b", "c"), hasItem("c")); assertThat(Lists.newArrayList("a", "b", "c"), not(hasItem("d"))); |
check if multiple elements are in a collection
1 |
assertThat(Lists.newArrayList("a", "b", "c"), hasItems("c", "d")); |
check all elements in a collection with strict order
1 |
assertThat(collection, contains("a", "b", "c")); |
check all elements in a collection with any order
1 |
assertThat(collection, containsInAnyOrder("a", "b", "c")); |
check if collection is empty
1 |
assertThat(Lists.newArrayList(), empty()); |
check if array is empty
1 |
assertThat(new String[] {"a"}, not(emptyArray())); |
check if Map is empty
1 |
assertThat(Maps.newHashMap(), equalTo(Collections.EMPTY_MAP)); |
check if Iterable is empty
1 |
assertThat(Lists.newArrayList(), emptyIterable()); |
check size of a collection
1 |
assertThat(Lists.newArrayList("a", "b", "c"), hasSize(3)); |
checking size of an iterable
1 |
assertThat(Lists.newArrayList("a", "b", "c"), Matchers.<String> iterableWithSize(3)); |
check condition on every item
1 |
assertThat(Lists.newArrayList(15, 20, 25, 30), everyItem(greaterThan(10))); |