# Replace JUnit Expected Annotation Property with assertThrows

# Description

Using the expected (opens new window) annotation property for testing the thrown exceptions is rather misleading. Often it becomes unclear which part of the test code is responsible for throwing the exception. This rule aims to overcome this problem by replacing the expected annotation property with assertThrows (opens new window) introduced in JUnit 4.13.

Requirements

This rule requires one of the following libraries to be present:

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

# Benefits

Improves the tests readability. Helps migrating to JUnit 5.

# Tags

# Code Changes

# Removing expected Property

Pre

@Test(expected = PersistenceException.class)
public void invalidRepo_shouldThrowPersistenceException() throws PersistenceException {
    User user = new User("10", "John", "wolf");
    invalidUserRepository.save(user);
}

Post

@Test
public void invalidRepo_shouldThrowPersistenceException() {
    User user = new User("10", "John", "wolf");
    assertThrows(PersistenceException.class, () -> invalidUserRepository.save(user));
}

# Multiple Annotation Properties

Pre

@Test(expected = PersistenceException.class, timeout = 500L)
public void timeoutInvalidRepo_shouldThrowPersistenceException() throws PersistenceException {
    User user = new User("10", "John", "wolf");
    invalidUserRepository.save(user);
}

Post

@Test(timeout = 500L)
public void timeoutInvalidRepo_shouldThrowPersistenceException() {
    User user = new User("10", "John", "wolf");
    assertThrows(PersistenceException.class, () -> invalidUserRepository.save(user));
}

# Limitations

@Test(expected=NullPointerException.class)
public void expectingRuntimeException() {
    User user = userRepository.findById("10");
    user.setName("John")
    userRepository.save(user);
    throwRuntimeException();
}

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 ReplaceJUnitExpectedAnnotationProperty
First seen in jSparrow version 3.24.0
Minimum Java version 8
Remediation cost 5 min
Links