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?