Unit testing a Roslyn Analyzer

  • It doesn’t allow syntax color coding and IntelliSense. These make it so much easier to visualize and write the code.
  • No compiler errors are generated. The code doesn’t have to compile correctly for the analyzer to run but, it’s good to have the compiler’s help.
  • It’s not possible to use the Syntax Visualizer on the strings. This tool is essential in development of diagnostic analyzers.

Adding the test sources to the unit tests project

I came up with this idea while developing another project that I spun-off from the analyzer. The NetFabric.CodeAnalysis repository is used to generate two NuGet packages:

Using the source files for unit testing

The classes DiagnosticVerifier and CodeFixVerifier used to validate the diagnostics are prepared to receive source strings. We now need to change the testing code to use the files.

Relative paths

It’s important that the build and tests can be executed anywhere the repository is cloned into. Including any continuous-integration agent.

Excluding files

I found two reasons to have source files excluded from the build:

  • The source doesn’t have to compile correctly for the analyzer to be run. It’s important that unit tests include these scenarios.
  • The fixed source files used to test the code fixers may not have enough changes to avoid naming collisions.

Sharing code

The test verifiers create an internal project where the source strings are added as documents:

  • The VerifyCSharpDiagnostic method has an overload that accepts an array of strings. These are all added to the internal project and the analyzer run on all of them.
  • The VerifyCSharpFix method only accepts one string. The analyzer and the code fixer are run on it and the result compared to the other string parameter.

Conclusion

It’s possible to take advantage of the IDE tools to develop the source code used to test an analyzer.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store