Java: exclude single-method classes from mocking

This commit is contained in:
Napalys Klicius
2025-08-11 11:25:30 +02:00
parent a9e9a62439
commit 53ccc56959
3 changed files with 3 additions and 2 deletions

View File

@@ -62,6 +62,8 @@ where
exists(MockitoMockCall mockCall |
mockCall.getParent+().(Stmt) = testMethod.getBody().getAStmt() and
mockedClassOrInterface = mockCall.getMockedType() and
// Only flag classes with multiple public methods (2 or more)
count(Method m | m = mockedClassOrInterface.getAMethod() and m.isPublic()) > 1 and
forex(Method method | method = mockedClassOrInterface.getAMethod() and method.isPublic() |
exists(MockitoMockingMethodCall mockedMethod |
mockedMethod.getMockitoMockCall() = mockCall and

View File

@@ -1,3 +1,2 @@
| TestORM.java:34:15:34:27 | nonCompliant1 | This test method mocks all public methods of a $@. | EmployeeRecord.java:4:14:4:27 | EmployeeRecord | class or an interface |
| TestORM.java:47:15:47:27 | nonCompliant2 | This test method mocks all public methods of a $@. | EmployeeRecord.java:4:14:4:27 | EmployeeRecord | class or an interface |
| TestORM.java:61:15:61:35 | compliantSingleMethod | This test method mocks all public methods of a $@. | EmployeeStatus.java:5:14:5:27 | EmployeeStatus | class or an interface |

View File

@@ -58,7 +58,7 @@ public class TestORM {
* When there's only one public method, mocking it doesn't indicate a "too big" test.
*/
@Test
public void compliantSingleMethod() { // $ SPURIOUS: Alert
public void compliantSingleMethod() {
EmployeeStatus statusMock = mock(EmployeeStatus.class); // COMPLIANT: Single public method, no choice but to mock it if needed
when(statusMock.getStatus()).thenReturn("inactive"); // Mocked EmployeeStatus.getStatus (the only public method, but that's OK)
}