docs/articles/nunit-analyzers/NUnit2056.md
| Topic | Value |
|---|---|
| Id | NUnit2056 |
| Severity | Info |
| Enabled | True |
| Category | Assertion |
| Code | UseAssertEnterMultipleScopeAnalyzer |
Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync.
Prior to NUnit 4.2, developers used two separate methods to group multiple assertions into a single logical assertion:
Assert.Multiple for synchronous codeAssert.MultipleAsync for asynchronous codeThis approach, while functional, had limitations — in particular around unnecessary context capture and limited static analysis due to the use of lambda expressions.
With the release of NUnit 4.2, a new API was introduced: Assert.EnterMultipleScope. This method unifies
the handling of multiple assertions for both sync and async code and avoids the problems above.
For more information on EnterMultipleScope see the discussion in this
Feature Request
[Test]
public void TestMultiple()
{
Assert.Multiple(() =>
{
var i = 4;
var j = 67;
Assert.That(i, Is.EqualTo(j));
});
}
and
[Test]
public async Task TestMultipleAsync()
{
await Assert.MultipleAsync(async () =>
{
var i = await GetInt();
var j = await GetInt();
Assert.That(i, Is.EqualTo(j));
});
}
The analyzer comes with a code fix that will replace Assert.Multiple and Assert.MultipleAsync
with using (Assert.EnterMultipleScope()) and keep the body of the methods as body of the using
statement. So the methods above will be changed into.
[Test]
public void TestMultiple()
{
using (Assert.EnterMultipleScope())
{
var i = 4;
var j = 67;
Assert.That(i, Is.EqualTo(j));
}
}
and
[Test]
public async Task TestMultipleAsync()
{
using (Assert.EnterMultipleScope())
{
var i = await GetInt();
var j = await GetInt();
Assert.That(i, Is.EqualTo(j));
}
}
Configure the severity per project, for more info see MSDN.
# NUnit2056: Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync
dotnet_diagnostic.NUnit2056.severity = chosenSeverity
where chosenSeverity can be one of none, silent, suggestion, warning, or error.
#pragma warning disable NUnit2056 // Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync
Code violating the rule here
#pragma warning restore NUnit2056 // Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync
Or put this at the top of the file to disable all instances.
#pragma warning disable NUnit2056 // Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync
[SuppressMessage][System.Diagnostics.CodeAnalysis.SuppressMessage("Assertion",
"NUnit2056:Consider using Assert.EnterMultipleScope statement instead of Assert.Multiple/Assert.MultipleAsync",
Justification = "Reason...")]