Skip to content

Instantly share code, notes, and snippets.

@jsteinshouer
Created April 18, 2025 12:53
Show Gist options
  • Select an option

  • Save jsteinshouer/eb19cadb3c2d4b2b35ed895c2943be77 to your computer and use it in GitHub Desktop.

Select an option

Save jsteinshouer/eb19cadb3c2d4b2b35ed895c2943be77 to your computer and use it in GitHub Desktop.
xUnit Test Runner for Jupyter Notebooks.
using System;
using System.Linq;
using System.Reflection;
using Xunit;
public class SimpleTestRunner
{
public static void RunTests(Type testClassType)
{
Console.WriteLine($"Running tests in {testClassType.Name}...");
// Create an instance of the test class
var testClassInstance = Activator.CreateInstance(testClassType);
// Get all methods with the [Fact] or [Theory] attribute
var testMethods = testClassType.GetMethods()
.Where(m => m.GetCustomAttributes(typeof(FactAttribute), false).Any() ||
m.GetCustomAttributes(typeof(TheoryAttribute), false).Any());
foreach (var method in testMethods)
{
var theoryData = method.GetCustomAttributes(typeof(InlineDataAttribute), false)
.Cast<InlineDataAttribute>();
if (theoryData.Any())
{
// Handle [Theory] with [InlineData]
foreach (var data in theoryData)
{
try
{
var parameters = data.GetData(method).ToArray<object[]>()[0];
Console.WriteLine($"Running {method.Name} with arguments: {String.Join(",", parameters)}...");
method.Invoke(testClassInstance, parameters);
Console.WriteLine($"✔ {method.Name} passed.");
}
catch (TargetInvocationException ex)
{
Console.WriteLine($"✘ {method.Name} failed: {ex.InnerException?.Message}");
if ( ex.InnerException?.GetType().Namespace != "Xunit.Sdk" )
{
Console.Write($"{ex.InnerException?.StackTrace}");
}
}
}
}
else
{
// Handle [Fact]
try
{
Console.WriteLine($"Running {method.Name}...");
method.Invoke(testClassInstance, null);
Console.WriteLine($"✔ {method.Name} passed.");
}
catch (TargetInvocationException ex)
{
Console.WriteLine($"✘ {method.Name} failed: {ex.InnerException?.Message}");
if ( ex.InnerException?.GetType().Namespace != "Xunit.Sdk" )
{
Console.Write($"{ex.InnerException?.StackTrace}");
}
}
}
}
}
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment