Skip to content

Commit 0e65b4e

Browse files
authored
Fix final field @InjectMock recipe (#679)
1 parent 26b1009 commit 0e65b4e

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/main/java/org/openrewrite/java/testing/mockito/NoInitializationForInjectMock.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ public String getDisplayName() {
3636

3737
@Override
3838
public String getDescription() {
39-
return "Removes unnecessary initialization for fields annotated with `@InjectMocks` in Mockito tests.";
39+
return "Removes unnecessary initialization for fields annotated with `@InjectMocks` in Mockito tests. If the" +
40+
" field was final, the final modifier is removed.";
4041
}
4142

4243
@Override
@@ -47,7 +48,10 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations v
4748
J.VariableDeclarations vd = super.visitVariableDeclarations(variableDeclarations, ctx);
4849

4950
if (isField(getCursor()) && new AnnotationService().matches(getCursor(), INJECT_MOCKS)) {
50-
return vd.withVariables(ListUtils.map(vd.getVariables(), it -> it.withInitializer(null)));
51+
return maybeAutoFormat(vd, vd
52+
.withModifiers(ListUtils.map(vd.getModifiers(), modifier -> modifier.getType() == J.Modifier.Type.Final ? null : modifier))
53+
.withVariables(ListUtils.map(vd.getVariables(), it -> it.withInitializer(null))),
54+
ctx, getCursor().getParentOrThrow());
5155
}
5256

5357
return vd;

src/test/java/org/openrewrite/java/testing/mockito/NoInitializationForInjectMockTest.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,40 @@ class MyTest {
6969
)
7070
);
7171
}
72+
73+
@Test
74+
void removeInitializationOfInjectMocksWithFinal() {
75+
//language=java
76+
rewriteRun(
77+
java(
78+
"""
79+
class MyObject {
80+
private String someField;
81+
82+
public MyObject(String someField) {
83+
this.someField = someField;
84+
}
85+
}
86+
"""
87+
),
88+
java(
89+
"""
90+
import org.mockito.InjectMocks;
91+
92+
class MyTest {
93+
@InjectMocks
94+
final MyObject myObject = new MyObject("someField");
95+
}
96+
""",
97+
"""
98+
import org.mockito.InjectMocks;
99+
100+
class MyTest {
101+
@InjectMocks
102+
MyObject myObject;
103+
}
104+
"""
105+
)
106+
);
107+
}
72108
}

0 commit comments

Comments
 (0)