diff --git a/docs/articles/nunit/writing-tests/attributes/cancelafter.md b/docs/articles/nunit/writing-tests/attributes/cancelafter.md index 279124870..88fa81aa8 100644 --- a/docs/articles/nunit/writing-tests/attributes/cancelafter.md +++ b/docs/articles/nunit/writing-tests/attributes/cancelafter.md @@ -37,16 +37,15 @@ When used on test methods, NUnit automatically adds an extra argument to your me ## Example -```csharp -[Test, CancelAfter(2000)] -public void RunningTestUntilCanceled(CancellationToken token) -{ - while (!token.IsCancellationRequested) - { - /* */ - } -} +The `CancelAfterAttribute` supports cancellation across a variety of ways to write tests. + +A simple test, written using the `Test` attribute: + +[!code-csharp[TestWithCancellationToken](~/snippets/Snippets.NUnit/Attributes/CancelAfterAttributeExamples.cs#TestWithCancellationToken)] +A parameterized test written using the `TestCase` attribute: + +```csharp [CancelAfter(2000)] [TestCase("http://server1")] [TestCase("http://server2")] @@ -60,6 +59,10 @@ public async Task PotentiallyLongRunningTest(string uri, CancellationToken token } ``` +A parameterized test written using the `TestCaseSource` attribute: + +[!code-csharp[TestCaseSourceWithCancellationToken](~/snippets/Snippets.NUnit/Attributes/CancelAfterAttributeExamples.cs#TestCaseSourceWithCancellationToken)] + > [!NOTE] > When debugging a unit test, i.e. when a debugger is attached to the process, the timeout is not enforced. diff --git a/docs/snippets/Snippets.NUnit/Attributes/CancelAfterAttributeExamples.cs b/docs/snippets/Snippets.NUnit/Attributes/CancelAfterAttributeExamples.cs new file mode 100644 index 000000000..06b7472ce --- /dev/null +++ b/docs/snippets/Snippets.NUnit/Attributes/CancelAfterAttributeExamples.cs @@ -0,0 +1,34 @@ +using NUnit.Framework; +#pragma warning disable NUnit1029 // Pending https://github.com/nunit/nunit.analyzers/issues/957 + +namespace Snippets.NUnit.Attributes +{ + public class CancelAfterAttributeExamples + { + #region TestWithCancellationToken + [Test, CancelAfter(2_000)] + public void RunningTestUntilCanceled(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + /* */ + } + } + #endregion + + #region TestCaseSourceWithCancellationToken + private static int[] _simpleValues = { 2, 4, 6, 8 }; + + [TestCaseSource(nameof(_simpleValues)), CancelAfter(1_000)] + public void TestCaseSourceWithCancellationToken(int a, CancellationToken cancellationToken) + { + Assert.That(cancellationToken, Is.Not.Default); + + while (!cancellationToken.IsCancellationRequested) + { + /* */ + } + } + #endregion + } +} diff --git a/docs/snippets/Snippets.NUnit/Snippets.NUnit.csproj b/docs/snippets/Snippets.NUnit/Snippets.NUnit.csproj index c0a965b60..33e29ff5c 100644 --- a/docs/snippets/Snippets.NUnit/Snippets.NUnit.csproj +++ b/docs/snippets/Snippets.NUnit/Snippets.NUnit.csproj @@ -10,7 +10,7 @@ - + all