Created
June 23, 2020 23:37
-
-
Save werwolfby/db728c98230376ae5b94eaa2dd479acd to your computer and use it in GitHub Desktop.
WithTimeout extension methods for use in UnitTests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class WithTimeoutExtension | |
{ | |
public static Task WithTimeout(this Task task, int timeout, string actionName = null) => task.WithTimeout(TimeSpan.FromMilliseconds(timeout), actionName); | |
public static async Task WithTimeout(this Task task, TimeSpan timeout, string actionName = null) | |
{ | |
var delay = Task.Delay(timeout); | |
var completedTask = await Task.WhenAny(task, delay); | |
if (completedTask == task) | |
{ | |
return; | |
} | |
Assert.Fail($"{actionName ?? "Task"} is not completed in {timeout} for {TestContext.CurrentContext.CurrentRepeatCount + 1} try"); | |
} | |
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, string actionName = null) | |
{ | |
var delay = Task.Delay(timeout); | |
var completedTask = await Task.WhenAny(task, delay); | |
if (completedTask == task) | |
{ | |
return task.GetAwaiter().GetResult(); | |
} | |
throw new AssertionException($"{actionName ?? "Task"} is not completed in {timeout} for {TestContext.CurrentContext.CurrentRepeatCount + 1} try"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment