且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从代码运行 NUnit - 如何将结果输出到控制台?

更新时间:2023-12-05 13:47:28

在运行测试之前尝试存储控制台的当前输出流

var currentOut = Console.Out;

然后在运行完成后将其设置回

Console.SetOut(currentOut);

此外,是否有一种内置方法可以列出给定 TestResults 实例的失败结果?

我一直找不到.但是,以下代码应该可以为您提供一些帮助.它递归地内省组合的 TestResult 结构并将每个测试的结果输出到控制台.

static void OutputResult(TestResult result){如果(结果.有结果){foreach (var childResult in result.Results){输出结果((TestResult)childResult);}返回;}Console.WriteLine("{0}:{1}", result.FullName, result.ResultState);}

I am running NUnit tests using RemoteTestRunner. In the end, I get a TestResult object containing the results. The unit test project compiles as a console application. The problem is, after running the tests, the output gets somehow redirected, and I can't print the results to the console.

Here's the code. It doesn't output anything, not even "Open, sesame!" (although it does run to the end - confirmed in the debugger).

Any suggestions?

Also, is there a built-in way to list the failed results, given the TestResults instance?

public static void Main()
{
    TestPackage testPackage = new TestPackage(AssemblyPath);
    RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
    remoteTestRunner.Load(testPackage);
    TestResult testResult = remoteTestRunner.Run(null);

    Console.WriteLine(testResult.IsFailure);

    Console.WriteLine("Open, sesame!");

}
public static string AssemblyPath
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return path;
    }
}

Try to store the current output stream of the Console before running the tests with

var currentOut = Console.Out;

Then setting it back once the run has been performed with

Console.SetOut(currentOut);

Also, is there a built-in way to list the failed results given the TestResults instance?

I haven't been able to find any. However, the following piece of code should provide you with some help. It recursively introspects the composed TestResult structure and outputs the result of each test to the console.

static void OutputResult(TestResult result)
{
    if(result.HasResults)
    {
        foreach (var childResult in result.Results)
        {
            OutputResult((TestResult)childResult);
        }
        return;
    }

    Console.WriteLine("{0}:{1}", result.FullName, result.ResultState);
}