You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[java] CloseResource: False positive on mocks #2840
Rule:CloseResource Description:
PMD plugin reports CloseResource violation when a closeable org.springframework.http.client.ClientHttpResponse is mocked. Code Sample demonstrating the issue:
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 directlyConnectionbar(Poolpool) {
Connectionc = pool.getConnection();
returnc;
}
// 2. resource declared inside a nested block and returnedConnectionbar(Poolpool, booleanflag) {
if (flag) {
Connectionc = pool.getConnection();
returnc;
}
returnnull;
}
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:
(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.
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.
@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:
So the false positive is alive. Two separate mistakes on my side, both of which made my "cannot reproduce" meaningless:
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.
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:
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.
@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.
Activity
[-][java] CloseResource false positive on mocks[/-][+][java] CloseResource: False positive on mocks[/+]lukasgraef commentedon Jun 23, 2026
Reproducer for a testcase:
Eljees commentedon Jul 30, 2026
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.isResourceVariableClosedchecksisReturnedByMethodalongside the try-with-resources check. I added two cases toCloseResource.xml, both withexpected-problems 0:I included the second one because
getMethodOfNodestops at the nearestASTBlockrather than the method body (isNotMethodaccepts any block), so I expected the outerreturnto be invisible from a nested declaration. It isn't — both pass:(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:
return wrap(response)), that is still reported —isReturnedByMethodfilters out accesses whose parent is a method call. Worth confirming with @giorgimode whether the real code returned the variable directly.AI-assisted (LLM used for drafting); the fixtures and the run above are mine.
UncleOwen commentedon Aug 5, 2026
@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.
[java] CloseResource: drop the two pmd#2840 test cases from this PR
Eljees commentedon Aug 6, 2026
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, sojava.io.Closeableandjava.lang.AutoCloseablewere switched off - which is exactly the family that makesMockRequest extends Closeablea 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.
Eljees commentedon Aug 6, 2026
@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 aCloseResource.xmlcase with stock configuration:So the false positive is alive. Two separate mistakes on my side, both of which made my "cannot reproduce" meaningless:
return c), which goes throughisReturnedByMethod— a branchCloseResource.xmlalready 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.<rule-property name="types">java.sql.Connection</rule-property>, and that property replaces the default list rather than extending it. The reporter'sMockRequest extends Closeableis only reachable through the defaultjava.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 servletgetReader()/getWriter()/getOutputStream()methods. Adding Mockito's factory to it makes the reproducer clean — same file, same run, second case:That is a mechanism already in the rule, so this could be closed either as documentation ("configure
allowedResourceMethodPatternsfor your mocking framework") or by shipping the common mock factories among the defaults. What I have verified is only the qualifiedMockito.mock(...)form; a statically importedmock(...),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.
UncleOwen commentedon Aug 6, 2026
@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.
[java] Fix #6742: CloseResource false positive for a wrapped resource…