Why is this an issue?
It should be clear to a casual reader what code a test is testing and what results are expected. Unfortunately, that’s not usually the case with
the ExpectedException
attribute since an exception could be thrown from almost any line in the method.
This rule detects MSTest and NUnit ExpectedException
attribute.
Noncompliant code example
<TestMethod>
<ExpectedException(GetType(ArgumentNullException))> ' Noncompliant
Public Sub TestNullArg()
'...
End Sub
Compliant solution
<TestMethod>
Public Sub TestNullArg()
Dim CallFailed As Boolean = False
Try
' ...
Catch ex As Exception
CallFailed = true
End Try
Assert.IsTrue(CallFailed, "Expected call to MyMethod to fail with ArgumentNullException")
End Sub
or
<TestMethod>
Public Sub TestNullArg()
Assert.ThrowsException(Of ArgumentNullException)(Sub() ... )
End Sub
Exceptions
This rule ignores one-line test methods, since it is obvious in such methods where the exception is expected to be thrown.