是的,我相信您需要创建自己的跑步者。下面提供了一个关于如何做到这一点的简单示例(您需要在 TestMethodRunnerCallback 方法中添加所需的逻辑:
namespace MyTestRunner
{
using System;
using System.Linq;
using Xunit;
public class Program
{
public static int Main(string[] args)
{
var testAssembly = TestAssemblyBuilder.Build(
new ExecutorWrapper(args[0], null, false));
var tests = testAssembly.EnumerateTestMethods(x => x
.DisplayName
.ToLowerInvariant();
var testMethods = (args.Length > 1 && !string.IsNullOrEmpty(args[1])
? tests.Contains(args[1].ToLowerInvariant())).ToList()
: tests.ToList();
if (testMethods.Count == 0)
return 0;
var runnerCallback = new TestMethodRunnerCallback();
testAssembly.Run(testMethods, runnerCallback);
return runnerCallback.FailedCount;
}
public class TestMethodRunnerCallback : ITestMethodRunnerCallback
{
public int FailedCount { get; private set; }
public void AssemblyFinished(TestAssembly testAssembly, int total, int failed, int skipped, double time)
{
FailedCount = failed;
}
public void AssemblyStart(TestAssembly testAssembly)
{
}
public bool ClassFailed(TestClass testClass, string exceptionType, string message, string stackTrace)
{
return true;
}
public void ExceptionThrown(TestAssembly testAssembly, Exception exception)
{
}
public bool TestFinished(TestMethod testMethod)
{
return true;
}
public bool TestStart(TestMethod testMethod)
{
return true;
}
}
}
}
编辑:
似乎在 xUnit.net 2.0 中 TestAssemblyBuilder 已被替换为 XunitFrontController。下面的代码显示了如何在测试运行时捕获测试通过的结果:
public class Program
{
public static void Main(string[] args)
{
string assemblyPath = @"path";
XunitFrontController controller = new XunitFrontController(
assemblyPath);
TestAssemblyConfiguration assemblyConfiguration = new TestAssemblyConfiguration();
ITestFrameworkDiscoveryOptions discoveryOptions = TestFrameworkOptions.ForDiscovery(assemblyConfiguration);
ITestFrameworkExecutionOptions executionOptions = TestFrameworkOptions.ForExecution(assemblyConfiguration);
IMessageSink messageSink = new CustomTestMessageVisitor<ITestMessage>();
Console.WriteLine("Running tests");
controller.RunAll(
messageSink: messageSink,
discoveryOptions: discoveryOptions,
executionOptions: executionOptions);
}
}
public class CustomTestMessageVisitor<T> : TestMessageVisitor<T> where T : ITestMessage
{
protected override bool Visit(ITestFinished message)
{
Console.WriteLine("Test {0} finished.",
message.Test.DisplayName);
return true;
}
protected override bool Visit(ITestPassed message)
{
Console.WriteLine("Test {0} passed", message.Test.DisplayName);
return true;
}
protected override bool Visit(ITestFailed message)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (string exceptionType in message.ExceptionTypes)
{
stringBuilder.AppendFormat("{0}, ", exceptionType);
}
Console.WriteLine("Test {0} failed with {1}",
message.Test.DisplayName,
stringBuilder.ToString());
return true;
}
}