Skip to content

fix: RemoveDoNothingForDefaultMocks incorrectly removes doNothing() in contexts where removal produces uncompilable code #1008

@darrencilia

Description

@darrencilia

What version of OpenRewrite are you using?

  • rewrite-testing-frameworks 3.36.0
  • rewrite-maven-plugin 6.40.0

How are you running OpenRewrite?

Maven plugin, single module project.

<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>6.40.0</version>
  <configuration>
    <activeRecipes>
      <recipe>org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_5</recipe>
    </activeRecipes>
  </configuration>
</plugin>

What is the smallest, simplest way to reproduce the problem?

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.BufferedWriter;
import java.util.List;
import static org.mockito.Mockito.doNothing;

@RunWith(MockitoJUnitRunner.class)
class MyTest {
    @Mock
    private BufferedWriter bufferedWriter;

    @Test
    public void test() {
        List<String> paths = List.of("/path/1", "/path/2");
        paths.forEach(path -> doNothing().when(bufferedWriter).write(path));
    }
}

What did you expect to see?

No change, doNothing() as an expression lambda body or switch expression arm should be retained.
The recipe cannot safely remove it because removing the method invocation leaves a dangling ->
producing uncompilable code. Examples:

paths.forEach(path ->);       // Expression lambda do not compile
case "ACTIVE" ->               // Switch arm do not compile

Block lambda and switch block arm cases are not affected, as removal leaves an empty block which is valid Java and can be cleaned up by static analysis.

What did you see instead?

@Test
public void test() {
    List<String> paths = List.of("/path/1", "/path/2");
    paths.forEach(path ->);  // does not compile
}

Full stack trace: N/A because no error thrown, recipe silently produces uncompilable code.
Are you interested in contributing a fix? Yes, a fix and tests are ready as a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions