-
Notifications
You must be signed in to change notification settings - Fork 237
Closed
Labels
False PositiveRule IS triggered when it shouldn't be.Rule IS triggered when it shouldn't be.
Milestone
Description
Description
S3431 is raised when [ExpectedException] is used for a test method. Some test methods rely on the logic of uncaught exceptions as the result of the execution. Forcing the developer to use other means than [ExpectedException] can make the test flow difficult to read.
Repro steps
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))] // FP. The attribute makes the test method much simpler.
public void UsingTest()
{
try
{
Console.ForegroundColor = ConsoleColor.Black;
using var _ = new ConsoleAlert();
Assert.AreEqual(ConsoleColor.Red, Console.ForegroundColor);
throw new InvalidOperationException();
}
finally
{
Assert.AreEqual(ConsoleColor.Black, Console.ForegroundColor); // We don't care about the exception itself but only about the code flow.
}
}
public sealed class ConsoleAlert : IDisposable
{
private readonly ConsoleColor previous;
public ConsoleAlert()
{
previous = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
}
public void Dispose() =>
Console.ForegroundColor = previous;
}Expected behavior
S3431 is not raised.
Actual behavior
S3431 is raised.
Known workarounds
The test code could be moved to a local function and the local function could be asserted to throw. This seems cumbersome, given that there is a simple attribute for this kind of situation. The rule should not raise if assertions are done in catch or finally blocks.
Related information
- C#/VB.NET Plugins version: latest
See also this issue on SQ and SonarSource/sonar-scanner-msbuild#1737 (comment)
Metadata
Metadata
Assignees
Labels
False PositiveRule IS triggered when it shouldn't be.Rule IS triggered when it shouldn't be.