Skip to content

Commit

Permalink
Do not consider Assert.That with TestDelegate to be a candidate for A…
Browse files Browse the repository at this point in the history
…ssert.Multiple
  • Loading branch information
manfred-brands committed Oct 21, 2023
1 parent 42f733f commit 5a4fb6f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,39 @@ public void Test()
}");
RoslynAssert.Valid(this.analyzer, testCode);
}

[Test]
public void AnalyzeWhenUsingAnonymousLambda()
{
var testCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@"
public void Test()
{
object? actualDeserialized = null;
Assert.That(() => actualDeserialized = Calculate(), Throws.Nothing);
Assert.That(actualDeserialized, Is.Not.Null);
static object? Calculate() => new object();
}");

RoslynAssert.Valid(this.analyzer, testCode);
}

[Test]
public void AnalyzeWhenUsingTestDelegate()
{
var testCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@"
public void Test()
{
object? actualDeserialized = null;
Assert.That(Calculate, Throws.Nothing);
Assert.That(actualDeserialized, Is.Not.Null);
void Calculate() => actualDeserialized = new object();
}");

RoslynAssert.Valid(this.analyzer, testCode);
}
}
}
19 changes: 17 additions & 2 deletions src/nunit.analyzers/UseAssertMultiple/UseAssertMultipleAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,13 @@ protected override void AnalyzeAssertInvocation(OperationAnalysisContext context
var previousArguments = new HashSet<string>(StringComparer.Ordinal);

// No need to check argument count as Assert.That needs at least one argument.
var assertArgument = assertOperation.Arguments[0].Syntax.ToString();
IArgumentOperation assertArgumentOperation = assertOperation.Arguments[0];
if (assertArgumentOperation.Value is IDelegateCreationOperation)
{
return;
}

var assertArgument = assertArgumentOperation.Syntax.ToString();

IOperation? statementBefore = null;
int firstAssert = -1;
Expand Down Expand Up @@ -139,7 +145,16 @@ private static bool IsIndependentAssert(HashSet<string> previousArguments, IOper
if (currentAssertOperation is not null)
{
// No need to check argument count as Assert.That needs at least one argument.
string currentArgument = currentAssertOperation.Arguments[0].Syntax.ToString();
IArgumentOperation argumentOperation = currentAssertOperation.Arguments[0];
if (argumentOperation.Value is IDelegateCreationOperation)
{
// Assert.That(() => { SomeCode }, Throws.Nothing);
// TODO: Should we delve into the lambda?
// For now state that it isn't mergeable inside an Assert.Multiple.
return false;
}

string currentArgument = argumentOperation.Syntax.ToString();

// Check if test is independent
return IsIndependent(previousArguments, currentArgument);
Expand Down

0 comments on commit 5a4fb6f

Please sign in to comment.