Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding reference assemblies to Roslyn analyzer code fix unit tests

I'm attempting to write a unit test to test a Roslyn analyzer code fix. Things have moved on since the introduction of analyzers and editing DiagnosticVerifier.Helper.cs is no longer the way ( https://www.productiverage.com/creating-a-c-sharp-roslyn-analyser-for-beginners-by-a-beginner )

My analyzer works on mvc ControllerBase derived types yet adding the name of the AspNetCore assemblies to the reference assemblies does not resolve the issue of my test not resolving the AspNetCore namespace includes in the test source code

var test = new VerifyCS.Test();
mytest.ReferenceAssemblies = test.ReferenceAssemblies.AddAssemblies( ImmutableArray.Create(new string[] { "Microsoft.AspNetCore.Mvc"}));

error CS0234: The type or namespace name 'AspNetCore' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)

EDIT: fixed, using:

mytest.ReferenceAssemblies = mytest.ReferenceAssemblies.WithPackages(ImmutableArray.Create(new PackageIdentity[] { new PackageIdentity("Microsoft.AspNetCore.Mvc.Core", "2.2.5") }));
like image 964
Levon Avatar asked Jun 19 '26 02:06

Levon


1 Answers

You need to use the long syntax of VerifyCS.Test:

await new VerifyCS.Test
{
    ReferenceAssemblies = referenceAssemblies,
    TestState =
    {
        Sources = {test },
        //ExpectedDiagnostics = {VerifyCS.Diagnostic().WithLocation(0).WithArguments("xxx")}
    }, // FixedCode = "yyy", etc.
}.RunAsync();

You can add assemblies and nuget packages:

var referenceAssemblies = ReferenceAssemblies.Default
    .AddPackages(ImmutableArray.Create(
        new PackageIdentity("serilog", "2.10.0"),
        new PackageIdentity("Othe.Package.Name", "1.2.0")
        )
    ).AddAssemblies(
      ImmutableArray.Create(
        "Microsoft.Extensions.DependencyInjection.Abstractions",
        "Microsoft.Extensions.Hosting",
        "Microsoft.Extensions.Hosting.Abstractions")
    );

BEWARE: the nuget packages are recovered only from the feeds specified in nuget.config, so, if you're using pacakages from an special feed, like your company's DevOps feed, you need to include it in this config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    ....
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="myCompanyFeed" value="https://mycompanyfeed.pkgs.visualstudio.com/_packaging/MyCoNuget/nuget/v3/index.json" />
  </packageSources>
  <disabledPackageSources>
    <clear />
  </disabledPackageSources>
</configuration>

Removing the <clear/> is another option, but less portable.

like image 62
JotaBe Avatar answered Jun 23 '26 04:06

JotaBe