0

Consider the code below.

MySolutuion.sln

using System;
using System.Linq;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;

public class MyApp
{
    public static void Main(string[] args)
    {
        MSBuildLocator.RegisterDefaults();

        var workspace = MSBuildWorkspace.Create();
        var solution = workspace
            .OpenSolutionAsync(@"/<PATH>/SolutionToAnalyse.sln")
            .Result;

        var project = solution.Projects.First();
        var compilation = project.GetCompilationAsync().Result;
        var documents = project.Documents.ToList();
        var document = documents.First(d => d.Name.Equals("Foo.cs"));
        var syntaxTree = document.GetSyntaxTreeAsync().Result;
        var root = syntaxTree!.GetRoot();
        var semanticModel = compilation!.GetSemanticModel(syntaxTree);

        // fetch myList.Any()
        var inVocExSyn = root.DescendantNodes().OfType<InvocationExpressionSyntax>().ToList()[0];
        var iSym = semanticModel.GetSymbolInfo(inVocExSyn).Symbol;
        // prints System.Collections.Generic.IEnumerable<int>.Any<int>()
        Console.WriteLine(iSym);
    }
}

SolutionToAnalyse.sln - contains one project and a file Foo.cs:

public class Foo
{
    public void FooMethod()
    {
        List<int> myList = new List<int>();

        if (myList.Any())
        {
            Console.WriteLine("List is not empty");
        }
    }
}

Running the program, e.g., by using dotnet run, it prints System.Collections.Generic.IEnumerable<int>.Any<int>(), which is the expected behavior.

However, if the program is executed from a test environment, for example, xUnit:

public class UnitTest
{
    [Fact]
    public void Test1()
    {
        MyApp.Main(new[] {""});
    }
} 

it prints an empty line as iSym is null. Why is that?

momo
  • 3,313
  • 2
  • 19
  • 37
  • What platform (.NET Core, .NET Framework) are your xUnit tests targeting? Which platform is the SolutionToAnalyse.sln targeting? – Jason Malinowski Apr 26 '21 at 17:53
  • @JasonMalinowski Everything in .NET 5.0. I tried to use MSTest instead of xUnit, but the result is the same. – momo Apr 26 '21 at 18:16
  • I switched all projects to .NET Core 3.1 and there, it works! I opened a new bug report on GitHub: https://github.com/dotnet/roslyn/issues/52954 – momo Apr 27 '21 at 08:33

0 Answers0