# Replace JUnit Timeout Annotation Property with assertTimeout

# Description

The JUnit Jupiter API (opens new window) provides timeout assertions, i.e., assertions that make sure an executable completes before a timeout is exceeded.
In JUnit 4 this is achieved by using the timeout (opens new window) property of @Test(timeout=...) annotation.

This rule removes the timeout annotation property and inserts an assertTimeout (opens new window) instead.

Requirements

This rule requires the following library to be present:

  • org.junit.jupiter:junit-jupiter-api:5.0.0

# Benefits

Improves the tests readability. Helps migrating to JUnit 5.

# Tags

# Code Changes

# Removing timeout Property

Pre

@Test(timeout=100)
public void timeoutTest() throws PersistenceException {
	userRepository.save(new User("10", "John", "Snow"));
}

Post

@Test
public void timeoutTest() throws PersistenceException {
	assertTimeout(ofMillis(100), () -> userRepository.save(new User("10", "John", "Snow")));
}

# Multiple Statements

Pre

@Test(timeout=100)
public void multipleStatements() throws PersistenceException {
	User user = new User("10", "John", "Snow");
	userRepository.save(user);
}

Post

@Test
public void multipleStatements() throws PersistenceException {
	assertTimeout(ofMillis(100), () -> {
		User user = new User("10", "John", "Snow");
		userRepository.save(user);
	});
}

# Multiple Annotation Properties

Pre

@Test(expected=PersistenceException.class, timeout=100)
public void multipleAnnotationProperties() throws PersistenceException {
	userRepository.save(new User("10", "John", "Stark"));
}

Post

@Test(expected=PersistenceException.class)
public void multipleAnnotationProperties() throws PersistenceException {
	assertTimeout(ofMillis(100), () -> userRepository.save(new User("10", "John", "Stark")));
}

You Want To Have Those Changes Done Automatically?

The automatic application of this rule is supported in the following jSparrow version:

# Properties

Property Value
Rule ID ReplaceJUnitTimeoutAnnotationProperty
First seen in jSparrow version 3.26.0
Minimum Java version 8
Remediation cost 5 min