小编vyr*_*yrp的帖子

在Jon Skeet的"TimeMachine"异步单元测试框架中是否需要ManuallyPumpedSynchronizationContext?

我刚看过Jon Skeet的视频课程,他在那里讨论了异步方法的单元测试.它是在付费网站上,但我在他的书中找到了类似于他所说的内容(只有Ctrl + F"15.6.3.单元测试异步代码").

完整的代码可以在他的github上找到,但为了我的问题,我已经简化了它(我的代码基本上是StockBrokerTest.CalculateNetWorthAsync_AuthenticationFailure_ThrowsDelayed()在内联TimeMachine和Advancer操作).

假设我们有一个类来测试失败的登录(没有单元测试框架来简化问题):

public static class LoginTest
{
    private static TaskCompletionSource<Guid?> loginPromise = new TaskCompletionSource<Guid?>();

    public static void Main()
    {
        Console.WriteLine("== START ==");

        // Set up
        var context = new ManuallyPumpedSynchronizationContext(); // Comment this
        SynchronizationContext.SetSynchronizationContext(context); // Comment this

        // Run method under test
        var result = MethodToBeTested();
        Debug.Assert(!result.IsCompleted, "Result should not have been completed yet.");

        // Advancing time
        Console.WriteLine("Before advance");
        loginPromise.SetResult(null);
        context.PumpAll(); // Comment this
        Console.WriteLine("After advance");

        // Check …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing async-await

7
推荐指数
1
解决办法
212
查看次数

标签 统计

async-await ×1

c# ×1

unit-testing ×1