Skip to content

NUnit1012

Mikkel Nylander Bundgaard edited this page Apr 25, 2020 · 2 revisions

NUnit1012

Async test method must have non-void return type.

Topic Value
Id NUnit1012
Severity Error
Enabled True
Category Structure
Code TestMethodUsageAnalyzer

Description

Async test method must have non-void return type.

Motivation

To prevent tests that will fail at runtime due to improper construction.

How to fix violations

Example Violation

[Test]
public async void NUnit1012SampleTest()
{
    var result = await Task.FromResult(true);
    Assert.That(result, Is.True);
}

Explanation

async methods should generally not return void in C#. For example if an exception is thrown (as they are in the case of an assertion violation), the exception is actually a part of the task object. If the return type is void, no such object exists, to the exception is effectively swallowed.

Fix

Make the async test method return a Task:

[Test]
public async Task NUnit1012SampleTest()
{
    var result = await Task.FromResult(true);
    Assert.That(result, Is.True);
}

Or modify the test to not use async behavior:

[Test]
public void NUnit1012SampleTest()
{
    var result = true;
    Assert.That(result, Is.True);
}

Configure severity

Via ruleset file.

Configure the severity per project, for more info see MSDN.

Via #pragma directive.

#pragma warning disable NUnit1012 // Async test method must have non-void return type.
Code violating the rule here
#pragma warning restore NUnit1012 // Async test method must have non-void return type.

Or put this at the top of the file to disable all instances.

#pragma warning disable NUnit1012 // Async test method must have non-void return type.

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("Structure", 
    "NUnit1012:Async test method must have non-void return type.",
    Justification = "Reason...")]
Clone this wiki locally