Skip to content

Instantly share code, notes, and snippets.

@martinandersen3d
Forked from tams89/Logic.cs
Created April 24, 2022 11:33
Show Gist options
  • Save martinandersen3d/5460a9e292293d17dab74bb983aaf09d to your computer and use it in GitHub Desktop.
Save martinandersen3d/5460a9e292293d17dab74bb983aaf09d 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);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment