Skip to content

Instantly share code, notes, and snippets.

@tams89
Last active April 24, 2022 11:33
Show Gist options
  • Save tams89/f89004508c2a836f8247 to your computer and use it in GitHub Desktop.
Save tams89/f89004508c2a836f8247 to your computer and use it in GitHub Desktop.
NUnit TestCaseSource Async
using System;
using System.Threading;
namespace MT.Tests
{
/// <summary>
/// An object containing some information.
/// </summary>
public class Logic
{
public int Id { get; set; }
}
/// <summary>
/// Contains functions to process information.
/// </summary>
public class LogicService
{
/// <summary>
/// A method to process the information.
/// </summary>
public void DoSomething(Logic logic)
{
Console.WriteLine(logic.Id); // Does something.
Thread.Sleep(1 * 1000); // Simulate time taken to do some work.
}
}
}
using System.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MT.Tests
{
[TestFixture]
public class Test
{
/// <summary>
/// Collection of test cases.
/// </summary>
private static IEnumerable<Logic> LogicCollection
{
get
{
var list = new List<Logic>();
for (var i = 0; i < 1000; i++)
list.Add(new Logic { Id = i });
return list;
}
}
/// <summary>
/// Typical implementation of TestCaseSource.
/// </summary>
/// <param name="logicTestCase"></param>
[TestCaseSource(nameof(LogicCollection))]
public void LogicTest(Logic logicTestCase)
{
// Default execution.
var service = new LogicService();
Assert.DoesNotThrow(() => service.DoSomething(logicTestCase));
}
/// <summary>
/// Async implementation, NOTE this binds to the NUnit Runner UI as-is.
/// i.e. individual test cases are still visible in the runner.
/// </summary>
/// <param name="logicTestCase"></param>
[TestCaseSource(nameof(LogicCollection))]
public void AsyncLogicTest(Logic logicTestCase)
{
// Task Parallel library executes each test case in a seperate background thread.
Task.Run(() =>
{
var service = new LogicService();
service.DoSomething(logicTestCase);
});
}
}
}
@tams89
Copy link
Author

tams89 commented Mar 12, 2016

This is a very simple example of how NUnit TestCaseSource can be run asynchronously, which if used in the context of integration tests can boost performance and significantly reduce execution time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment