Back to Nunit

NUnit1013

docs/articles/nunit-analyzers/NUnit1013.md

latest3.0 KB
Original Source

NUnit1013

The async test method must have a non-generic Task return type when no result is expected

TopicValue
IdNUnit1013
SeverityError
EnabledTrue
CategoryStructure
CodeTestMethodUsageAnalyzer

Description

The async test method must have a non-generic Task return type when no result is expected.

Motivation

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

How to fix violations

Example Violation

csharp
[TestCase(1)]
public async Task<string> NUnit1013SampleTest(int numberValue)
{

    return await ConvertNumber(numberValue);
}

public Task<string> ConvertNumber(int numberValue)
{
    return Task.FromResult(numberValue.ToString());
}

Explanation

The NUnit ExpectedResult syntax is not used, so it's an error for this method to return something that isn't being checked.

Fix

Utilize the ExpectedResult syntax:

csharp
[TestCase(1, ExpectedResult = "1")]
public async Task<string> NUnit1013SampleTest(int numberValue)
{
    return await ConvertNumber(numberValue);
}

public Task<string> ConvertNumber(int numberValue)
{
    return Task.FromResult(numberValue.ToString());
}

Or, use an assertion and a generic Task rather than Task<string>:

csharp
[TestCase(1)]
public async Task NUnit1013SampleTest(int numberValue)
{
    var result = await ConvertNumber(numberValue);
    Assert.That(result, Is.EqualTo("1"));
}

public Task<string> ConvertNumber(int numberValue)
{
    return Task.FromResult(numberValue.ToString());
}
<!-- start generated config severity -->

Configure severity

Via ruleset file

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

Via .editorconfig file

ini
# NUnit1013: The async test method must have a non-generic Task return type when no result is expected
dotnet_diagnostic.NUnit1013.severity = chosenSeverity

where chosenSeverity can be one of none, silent, suggestion, warning, or error.

Via #pragma directive

csharp
#pragma warning disable NUnit1013 // The async test method must have a non-generic Task return type when no result is expected
Code violating the rule here
#pragma warning restore NUnit1013 // The async test method must have a non-generic Task return type when no result is expected

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

csharp
#pragma warning disable NUnit1013 // The async test method must have a non-generic Task return type when no result is expected

Via attribute [SuppressMessage]

csharp
[System.Diagnostics.CodeAnalysis.SuppressMessage("Structure",
    "NUnit1013:The async test method must have a non-generic Task return type when no result is expected",
    Justification = "Reason...")]
<!-- end generated config severity -->