Search code examples
c#.netnunit

How to automatically convert all assertions of a "classical model" into assertions of a "constraint model" in NUnit?


Is there a tool to automatically convert "classical model" assertions into "constraint model" assertions for all tests?

The Nuget package NUnit.Analyzers offers automatic refactoring, but it only works for a single assertion.

For example, Classical model:

Assert.IsTrue(sut.Value);

Constraint model:

Assert.That(sut.Value, Is.True);

Solution

  • First thing, you might use Regex to convert all Assert. to ClassicAssert. so that the code would compile.

    When I did this in my own project, I proceeded with this approach to do the whole thing. I wrote a Regex for each pattern with a capturing group in replacement. It worked fine.

    But now for this question, I found a better way to automate this. I didn't realise there was an analyzer suggestion for it.

    In Visual Studio, VS Code, or Rider, you can select any quick fix and apply it to the whole document, project, or solution.

    But even without that, you can run the fix from the command prompt like that:

     dotnet format *.csproj --diagnostics NUnit2003 --severity info
    

    You can use a specific csproj or sln file as needed. NUnit2003 is the code of the fix that I saw in my simple test, and you need --severity info because these are not included by default even if you name the diagnostic you are fixing.