[ExpectedExceptionAttribute] is an anti-pattern

Hi,

I’m a frequent user of the [ExpectedExceptionAttribute] but found out lately that its use is not recommended (anymore).

While the class itself is not deprecated, there are good reasons to use the Assert.ThrowsException() or Assert.ThrowsExceptionAsync() when writing unit tests.

A full explanation can be found here: Finally: Proper Exception Assertion in MSTest | Jim’s Rules Regarding Everything

I believe a SonarCloud rule would make sense here - it can be low-level (reported as a Minor)

Please let me know what you think.

Best regards
Norbert

It should not be too hard (as in: it is easy) to implement this. Are you aware of other test frameworks that als support this obsolete/anti-pattern approach?

I gave it a try: New rule: Use an Assert method to test if a specific exception was thrown by Corniel · Pull Request #4628 · SonarSource/sonar-dotnet · GitHub

1 Like

Nice hand - I hope your contributions makes it into the product :muscle:

The team has a busy schedule, so it still will take some time.

@norberth

Please take a look at rule 3431 as I believe that your suggestion is actually matching an existing rule.

1 Like

It very much looks like it - not sure why it never triggered. I have to review my unit tests.

Thanks
Norbert

Oops… Anyway, I added a VB.NET implementation as well.

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