The match in the constructor itself is correct as it throws a runtime exception, but the 2 matches with Collections.emptyList() are wrong, because also the cast inside can not fail in my oppinion.
// given
public FooService(List<String> a, List<String> b) {
Objects.requireNonNull(a, "a must not be null");
Objects.requireNonNull(b, "b must not be null");
if (a.isEmpty() && b.isEmpty()) {
throw new IllegalArgumentException();
}
}
// then this should not fail in java:S5778
assertThatThrownBy(() -> new FooService(Collections.emptyList(), Collections.emptyList())).isInstanceOf(IllegalArgumentException.class);
So from my understanding Sonar thinks that Collections.emptyList() can throw an exception, I think it can not.
The problem with this assertion is that it is not clear at first glance which method call/new class is supposed to throw the expected Runtime Exception. Even if I can guess that Collections.emptyList() is not throwing any Exception and that it should be the class creation, I had to manually check emptyList() code to be 100% sure about it.
That’s exactly the spirit of the rule: we want to avoid guesses and manual verifications in tests.
That being said, I understand your concern, there are indeed situations where it could seem superfluous. If you strongly believe the code is fine as it is, you can mark it as “Won’t fix”.
That clarifies it.
I had the assumption that the rule really analyzes if multiple exceptions can occur, but then it’s more related to readability.
Maybe it makes sense to whitelist some methods that can be used safely.