Skip to content

Instantly share code, notes, and snippets.

@duongphuhiep
Last active May 24, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duongphuhiep/410e32a2b4710656900e88a24190b3bb to your computer and use it in GitHub Desktop.
Save duongphuhiep/410e32a2b4710656900e88a24190b3bb to your computer and use it in GitHub Desktop.
xUnit test launcher
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using Xunit.Runners;
using log4net;
using Newtonsoft.Json;
using System.IO;
namespace Utils.Xunit
{
/// <summary>
/// A test launcher
/// https://github.com/xunit/xunit/issues/542
/// </summary>
public class AsyncTestRunner
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncTestRunner));
/// <summary>
/// Run the xunit test and return a report
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Task<TestsReport> Run(string assemblyFilePath)
{
Log.Info($"Run {assemblyFilePath}");
var fi = new FileInfo(assemblyFilePath);
assemblyFilePath = fi.FullName;
var r = AssemblyRunner.WithAppDomain(assemblyFilePath);
var e = new ManualResetEvent(false);
var report = new TestsReport();
r.OnDiscoveryComplete = i =>
{
Log.Debug($"OnDiscoveryComplete {JsonConvert.SerializeObject(i)}");
};
r.OnExecutionComplete = i =>
{
report.Resume = i;
if (i.TestsFailed > 0)
Log.Error($"OnExecutionComplete ({i.TestsFailed} tests failed) {JsonConvert.SerializeObject(i)}");
else
Log.Info($"OnExecutionComplete (OK)" + JsonConvert.SerializeObject(i));
e.Set();
};
r.OnErrorMessage = i =>
{
report.Error = i;
Log.Error($"OnErrorMessage" + JsonConvert.SerializeObject(i));
e.Set();
};
r.OnTestPassed = i =>
{
report.AddTestResult(i);
Log.Debug($"OnTestPassed {i.MethodName}" + JsonConvert.SerializeObject(i));
};
r.OnTestFailed = i =>
{
report.AddTestResult(i);
Log.Info($"OnTestFailed {i.MethodName}" + JsonConvert.SerializeObject(i));
};
r.OnTestSkipped = i =>
{
report.AddTestResult(i);
Log.Debug($"OnTestSkipped {i.MethodName}" + JsonConvert.SerializeObject(i));
};
r.Start();
return Task.Run(() =>
{
e.WaitOne();
e.Dispose();
return report;
});
}
}
}
AsyncTestRunner.Run(@"My_Unit_Test.dll");
t.Wait();
var testReport = t.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit.Runners;
namespace Utils.Xunit
{
/// <summary>
/// A bag to save the report temporary,
/// this object will be transform to json to return
/// </summary>
public class TestsReport
{
public ErrorMessageInfo Error;
public ExecutionCompleteInfo Resume;
public List<TestInfo> Details = new List<TestInfo>();
public void AddTestResult(TestInfo r)
{
Details.Add(r);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment