I am trying to write a unit test for a simple Roslyn Source Generator based on the example here.

Successfully ran both MsTest as well XUnit Tests as demonstrated in the Section B of the Unit testing of generators in the cookbook here.

My full solution that I ran is here for you to see.

The problem is as follows. I added a bit more code to the generator. It now looks as below.

            context.AddSource("MyGeneratedFile.cs", SourceText.From(@"
namespace GeneratedNamespace
{
    public class GeneratedClass
    {
        public static void GeneratedMethod()
        {
            // generated code
            System.Console.WriteLine(""Hello..."");
        }
    }
}", Encoding.UTF8));
        }

Note that I added the following line

System.Console.WriteLine(""Hello..."");

Now when I run the test, the test fails. Looking into the diagnostic object I see the following error.

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

Definitely I am missing something.

New to Roslyn stuff, so how can I make the test pass? How do I add some references to the assembly that holds System namespace?

One way is to simply comment out the offending line, and yes its passing that way. But I am curious. How do I attach the required assembly that it is looking for?

Update

As @Youssef13 suggested, I added the MetadataReference for the console type

So that issue is gone, but now the following appears.

error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

I tried to add another MetadataReference for System.Object here, but this did not resolve it, the above persists.

How do I add a ref to System.Runtime?

Update 2.

Now I resolved it by adding the ref as follows. Take a look at it here.

var systemRuntime = Assembly.Load("System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
var systemRuntimeRef = MetadataReference.CreateFromFile(systemRuntime.Location);
1

There are 1 answers

1
Youssef13 On

I very very recommend the "Solution A" of the unit testing from the document you linked. But for "Solution B", you'll have to provide the assembly containing Console class. You can do that using:

MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)

There is an IEnumerable<MetadataReference> parameter for CSharpCompilation.Create.

The testing library, however, does include everything you need for whatever .NET version you want. Which is more flexible.