# 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();
}

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID ReplaceJUnitExpectedAnnotationProperty
First seen in jSparrow version 3.24.0
Minimum Java version 8
Remediation cost 5 min
Links