Skip to content

[java] CloseResource: False positive on mocks #2840

Closed

Description

@giorgimode

Affects PMD Version:
6.28.0+
7.0.0

Rule: CloseResource
Description:
PMD plugin reports CloseResource violation when a closeable org.springframework.http.client.ClientHttpResponse is mocked.
Code Sample demonstrating the issue:

Test:

ClientHttpResponse clientHttpResponse = mock(ClientHttpResponse.class);
 when(execution.execute(request, body)).thenReturn(clientHttpResponse);

Target code:

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);
        return response;
    }

Expected outcome:
No violation is reported.

Running PMD through: Gradle

Activity

  1. added
    a:bug
    on Oct 19, 2020
  2. added
    a:false-positive
    and removed
    a:bug
    on Jan 17, 2021
  3. added
    needs:pmd7-revalidation
    and removed
    needs:pmd7-revalidation
    on Mar 17, 2024
  4. changed the title [-][java] CloseResource false positive on mocks[/-] [+][java] CloseResource: False positive on mocks[/+] on Jun 9, 2026
  5. lukasgraef commented on Jun 23, 2026

    @lukasgraef
    Member

    Reproducer for a testcase:

    import java.io.Closeable;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.mockito.Mockito;
    
    interface MockRequest extends Closeable {
        int execute(String request, String body);
    }
    
    class MockTest {
        @Test
        void testMock() {
            MockRequest mock = Mockito.mock(MockRequest.class);
            Mockito.when(mock.execute("foo", "bar")).thenReturn(200);
    
            Assertions.assertEquals(200, mock.execute("foo", "bar"));
        }
    }
  6. Eljees commented on Jul 30, 2026

    @Eljees
    Contributor

    I could not reproduce this on current main (7.27.0-SNAPSHOT), in either the reported shape or a stricter variant, so this may be fixable by closing.

    The rule already treats a returned resource as closed — CloseResourceRule.isResourceVariableClosed checks isReturnedByMethod alongside the try-with-resources check. I added two cases to CloseResource.xml, both with expected-problems 0:

    // 1. the reported shape: resource returned directly
    Connection bar(Pool pool) {
        Connection c = pool.getConnection();
        return c;
    }
    
    // 2. resource declared inside a nested block and returned
    Connection bar(Pool pool, boolean flag) {
        if (flag) {
            Connection c = pool.getConnection();
            return c;
        }
        return null;
    }

    I included the second one because getMethodOfNode stops at the nearest ASTBlock rather than the method body (isNotMethod accepts any block), so I expected the outer return to be invisible from a nested declaration. It isn't — both pass:

    mvn -pl pmd-java test -Dtest=CloseResourceTest
    Tests run: 101, Failures: 0, Errors: 0, Skipped: 0
    BUILD SUCCESS
    

    (99 existing cases + the 2 above, on temurin-25; the build needs a JDK newer than 17.)

    So whatever produced the violation in 6.28/7.0 seems to be gone. Two things that would let you close this with confidence rather than on my word:

    • if the original code had the resource wrapped on the way out (return wrap(response)), that is still reported — isReturnedByMethod filters out accesses whose parent is a method call. Worth confirming with @giorgimode whether the real code returned the variable directly.
    • if you want the two cases above kept as regression tests, say so and I will open a PR with just them.

    AI-assisted (LLM used for drafting); the fixtures and the run above are mine.

  7. UncleOwen commented on Aug 5, 2026

    @UncleOwen
    Member

    @Eljees Have you tried the code posted by @lukasgraef ? It still causes a violation.

    Your code has no mocks at all, so I don't see how it is related to this issue.

  8. added a commit that references this issue on Aug 6, 2026
  9. Eljees commented on Aug 6, 2026

    @Eljees
    Contributor

    You're right, and my earlier comment was wrong. Sorry for the noise.

    I re-ran @lukasgraef's snippet verbatim against PMD 7.26.0 with CloseResource at its default settings, and it does report:

    MockTest.java:13: CloseResource: Ensure that resources like this MockRequest object are closed after use

    What went wrong on my side is worth writing down, because it invalidates the conclusion rather than just the wording. Both cases I added to CloseResource.xml carried <property name="types" value="java.sql.Connection"/>. That property replaces the default type list instead of extending it, so java.io.Closeable and java.lang.AutoCloseable were switched off - which is exactly the family that makes MockRequest extends Closeable a resource in the first place. Running the same file with that property set gives zero violations, so my test was structurally incapable of showing the bug.

    And you're right that my cases had no mocks in them: they were about a returned resource, which is a different code shape and is already covered a few hundred lines up in the same file. Please disregard that comment - the issue is live.

    If it would help, I can put up a failing test case for the reported shape (default properties, mock assigned to a local and never closed) so the issue has a reproducer inside the test suite rather than in a comment.

    AI-assisted (LLM used for drafting); the runs above are mine.

  10. Eljees commented on Aug 6, 2026

    @Eljees
    Contributor

    @UncleOwen You are right on both counts, and my earlier comment was wrong. I have now run @lukasgraef's snippet verbatim on current main (443f7a6), as a CloseResource.xml case with stock configuration:

    PROBE 2840 verbatim reproducer from lukasgraef
     -> Expected 0 problem(s), 1 problem(s) found.
    Tests run: 100, Failures: 1
    

    So the false positive is alive. Two separate mistakes on my side, both of which made my "cannot reproduce" meaningless:

    1. I tested a different shape. My cases returned the resource (return c), which goes through isReturnedByMethod — a branch CloseResource.xml already covers twice. In the reproducer the mock is never returned at all, so nothing I wrote touched this issue. As you say, there were no mocks in my code.
    2. My fixture disabled the very thing under test. I set <rule-property name="types">java.sql.Connection</rule-property>, and that property replaces the default list rather than extending it. The reporter's MockRequest extends Closeable is only reachable through the default java.lang.AutoCloseable, so even with the right shape my case could not have caught it.

    Sorry for the noise — I should have run the reporter's code before writing anything.

    One thing that may be useful now that the run is set up. The rule already has an extension point for exactly this class of "resource that is not really a resource": allowedResourceMethodPatterns, currently defaulted to the servlet getReader()/getWriter()/getOutputStream() methods. Adding Mockito's factory to it makes the reproducer clean — same file, same run, second case:

    <rule-property name="allowedResourceMethodPatterns">org.mockito.Mockito#mock(_*)</rule-property>
    PROBE A: verbatim reproducer, stock config          -> 1 problem  (fails)
    PROBE B: same code + the pattern above              -> 0 problems (passes)
    Tests run: 101, Failures: 1
    

    That is a mechanism already in the rule, so this could be closed either as documentation ("configure allowedResourceMethodPatterns for your mocking framework") or by shipping the common mock factories among the defaults. What I have verified is only the qualified Mockito.mock(...) form; a statically imported mock(...), spy(...), EasyMock and friends I have not checked, and the default-list question is a maintainer call about scope.

    Happy to open a PR for whichever direction you prefer, including "neither".

    AI-assisted (LLM used for drafting and for running the checks above); the runs and the conclusions are mine.

  11. UncleOwen commented on Aug 6, 2026

    @UncleOwen
    Member

    @Eljees How about both? Add support for Mockito (which I think is the most commonly used mocking framework and for which you've already done the research on what has to be added to allowedResourceMethodPatterns) to the defaults in errorprone.xml, and add a note in the rule doc for the other frameworks.

  12. added a commit that references this issue on Aug 7, 2026
  13. added this to the 7.27.0 milestone on Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions