With the @RunWith(MyRunner.class)
annotation on the test class:
Common Runners :
- Spring :
@RunWith(SpringJUnit4ClassRunner.class)
- Spring-Boot :
@RunWith(SpringRunner.class)
Spring Boot features - Testing - Mockito :
@RunWith(MockitoJUnitRunner.class)
http://site.mockito.org/ - JMockit :
@RunWith(JMockit.class)
http://jmockit.github.io/ - PowerMock :
@RunWith(PowerMockRunner.class)
http://powermock.github.io/
With the @FixMethodOrder
annotation on the test class:
@RunWith(MonRunnerHabituel.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SomeTest {
@Test
public void test_1_first() {
System.out.println("first executed test");
}
@Test
public void test_2_second() {
System.out.println("second executed test");
}
@Test
public void test_3_third() {
System.out.println("third executed test");
}
}
NAME_ASCENDING
)
For example, for a test that performs a remote service call (to be avoided) or a local HTTP server mock, it is advisable to set a delay. So that JUnit can stop the test if it lasts too long.
Simply with @Test
:
@Test(timeout = 10_000)
public void should_test() {
callHttpService();
}
ℹ️ Timeout in milliseconds.
⚠️ JUnit JavaDoc : Test methods with a timeout parameter are run in a thread other than the thread which runs the fixture's @Before and @After methods.
Simply with @Test
:
@Test(expected = TechnicalException.class)
public void should_test() {
callService();
}
With @Rule
:
On the test class:
@Rule
public final ExpectedException expectedEx = ExpectedException.none();
In the test method:
@Test
public void should_test() {
expectedEx.expect(TechnicalException.class);
expectedEx.expectMessage("my expected message");
callService();
}
Validate an exception cause:
@Test
public void should_test() {
expectedEx.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
expectedEx.expectMessage("my expected message");
callService();
}
Simply with @Ignore
:
@Test
@Ignore
public void should_test() {
callService();
}
With the Maven Surefire plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/IgnoredTest1*</exclude>
<exclude>**/IgnoredTest2*</exclude>
</excludes>
</configuration>
</plugin>
With @Category
annotation.
First step Define an annotation like this one:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyLocalTest {
}
Second step Configure the Maven Surefire plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<groups></groups>
<excludedGroups>com.myorg.category.MyLocalTest</excludedGroups>
</configuration>
</plugin>
Third step Add the @Category
annotation with your own annotation on the categorized tests:
@Test
@Category(MyLocalTest.class)
public void should_be_ignored_by_maven() {
callService();
}