You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.publicvoidUsingTest(){try{
Console.ForegroundColor = ConsoleColor.Black;usingvar_=new ConsoleAlert();
Assert.AreEqual(ConsoleColor.Red, Console.ForegroundColor);thrownew InvalidOperationException();}finally{
Assert.AreEqual(ConsoleColor.Black, Console.ForegroundColor);// We don't care about the exception itself but only about the code flow.}}publicsealedclassConsoleAlert:IDisposable{privatereadonlyConsoleColorprevious;publicConsoleAlert(){previous= Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;}publicvoidDispose()=>
Console.ForegroundColor =previous;}
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.
sebastien-marichal
changed the title
Fix S3431 FP: Don't raise if assertions are done in finally
Fix S3431 FP: Don't raise if assertions are done in catch or finally
Aug 7, 2024
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
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
orfinally
blocks.Related information
See also this issue on SQ and SonarSource/sonar-scanner-msbuild#1737 (comment)
The text was updated successfully, but these errors were encountered: