简体   繁体   中英

Capture c# MSBuild output when building a test project with XUnit

I am testing a custom msbuild task. So I have a test function like this, following this answer: https://stackoverflow.com/a/10718438/4126652

The basic idea is I build a test project that tries to run my task. I want the build logs that include my task logs to appear in the test console output.

[Fact]
public void TestFullProjectBuild()
{
    List<ILogger> loggers = new() {new ConsoleLogger()}; // Ilogger, ConsoleLogger is from using Microsoft.Build.Framework, using Microsoft.Build.Logging
    var projectCollection = new ProjectCollection();
    projectCollection.RegisterLoggers(loggers);
    string fixtureDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fixtures");
    string projPath = Path.Combine(fixtureDir, "TestProject.csproj.xml");
    var project = projectCollection.LoadProject(projPath);
    var ok = project.Build();
    projectCollection.UnregisterAllLoggers();
    Assert.True(ok);
}

Now this doesn't produce any build logs to my test console output. Searching in google and stackoverflow tells me that the only way to get console output in Xunit is to use ITestOutputHelper .

But I don't know how to pass that as the logger to MSBuild.

Any help is appreciated. I want my project.Build() console output to be captured by the test output

I figured out how to solve this:

We can create a separate XunitLogger like this:

public class XunitLogger: ConsoleLogger
{
    public XunitLogger(ITestOutputHelper testOutputHelper)
    {
        base.WriteHandler = testOutputHelper.WriteLine;
    }
}

And we can use it like this:

public class PatcherTest
{
    private readonly XunitLogger _xunitLogger;

    public PatcherTest(ITestOutputHelper testOutputHelper)
    {
        _xunitLogger = new XunitLogger(testOutputHelper);
    }

    [Fact]
    public void TestFullProjectBuild()
    {
        List<ILogger> loggers = new() { _xunitLogger };
        var projectCollection = new ProjectCollection();
        projectCollection.RegisterLoggers(loggers);
        string fixtureDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fixtures");
        string projPath = Path.Combine(fixtureDir, "TestProject.csproj.xml");
        var project = projectCollection.LoadProject(projPath);
        var ok = project.Build();
        projectCollection.UnregisterAllLoggers();
        Assert.True(ok);
    }
}

This will print the test build output as part of the console test output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM