Whitelisting calls to standard methods to avoid multiple invocation for runtime exception warnings

Hi,

I’m using Java with SonarCloud & SonarLint (plugin 7.4.0.60471 for IntelliJ).

I am having what I consider false-positive for the rule java:S5778 “Only one method invocation is expected when testing runtime exceptions”

I think there are some cases where it can be known that some method won’t raise an exception and it should be accepted in order to increase readability. I think it could work as a whitelist of methods.

	@Test
	public void testAnswerWithNonExistingTask() throws ServiceException {
		Assertions.assertThatThrownBy(() -> service.answer("not-a-task", "user", Collections.emptyMap()))
				.isInstanceOf(NotFoundException.class);
	}

In this case, I know that Collections.emptyMap() won’t fail and adding a temporary variable to hold it does not improve readability. I also tried with Map.of() instead but the same issue exists.

Regards,

In addition to the methods already mentionned, I also encountered the following ones that it would be worth withelisting (I added also the previous ones to get a clear list):

  • Collections.unmodifiableMap()
  • Collections.singletonMap()
  • List.of()
  • Map.of()
  • Collections.emptyList()
  • Collections.emptyMap()

Hello @NathanEckert,

Thanks for the report. You’re right your case is definitely a FP. And it looks like this rule’s implementation requires some improvements. Adding a whitelist of methods could be one of the solution. But I’m not sure this is the best one.

Anyway thanks for the report. Here is the link to track the issue:

https://sonarsource.atlassian.net/browse/SONARJAVA-4426

Regards,
Margarita

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.