Hello everyone,
I’m facing a java:S5783 issue on a test code like this :
@Test
void testGetOffersWhenException() {
try {
// Configuring mocks
SystemFault systemFault = new SystemFault();
systemFault.setErrorCode("500");
systemFault.setFaultDescription("Error");
// can throw SystemException
when(serviceMock.myMethod(any(myClass.class)))
.thenThrow(new SystemException("", systemFault));
when(propertiesMock.getEnv()).thenReturn("DEV");
// Executing
Request request = createRequest();
// can throw commonsException
myClass.getResponseElement(request);
fail("Executing - Exception should be thrown");
} catch (commonsException ex) {
assertThat(ex).isNotNull();
} catch (SystemException ex) {
fail("Configuring - Exception should not be thrown");
}
}
In this case the two different exceptions are correctly catches by two different cases, but sonar detect it as “multiple invocations throwing the same checked exception”.
It recommands to refactor the code like this
@Test
void testGetOffersWhenException() {
try {
// Configuring mocks
SystemFault systemFault = new SystemFault();
systemFault.setErrorCode("500");
systemFault.setFaultDescription("Error");
// can throw SystemException
when(serviceMock.myMethod(any(myClass.class)))
.thenThrow(new SystemException("", systemFault));
when(propertiesMock.getEnv()).thenReturn("DEV");
} catch (SystemException ex) {
fail("Configuring - Exception should not be thrown");
}
try {
// Executing
Request request = createRequest();
// can throw commonsException
myClass.getResponseElement(request);
fail("Executing - Exception should be thrown");
} catch (commonsException ex) {
assertThat(ex).isNotNull();
}
}
What doesn’t look like a better solution.
Can you confirm you can reproduce it and can I consider this as a false positive or do I missed something ?
SonarQube used : SonarQube Cloud entreprise + SonarQube for IDE (IntelliJ V11.15.0.84329)
Language : Java
Java version : 21