【问题标题】:Testing function containing async function in Dart在 Dart 中测试包含异步函数的函数
【发布时间】:2018-03-04 06:40:13
【问题描述】:

我想测试一个调用其他异步函数的函数,但我不知道如何编写它。函数是这样的:

function(X x, Y y) {
    x.doSomethingAsync().then((result) {
        if (result != null) {
            y.doSomething();
        }
    }
}

我想模拟 X 和 Y,运行 X,然后验证 y.doSomething() 是否被调用。但是我不知道如何等待x.doSomethingAsync() 完成。我正在考虑在断言之前做一些等待,但这似乎不是可靠的解决方案。
请问有什么帮助吗? :)

【问题讨论】:

    标签: unit-testing dart flutter


    【解决方案1】:

    你可以在飞镖中使用async/await。这将大大简化您的功能:

    function(DoSomething x,  DoSomething y) async {
      final result = await x.doSomethingAsync();
      if (result != null) {
        y.doSomething();
      }
    }
    

    这样,在x.doSomething 完成之前,函数不会完成。然后,您可以使用相同的 async/await 运算符和异步 test 来测试您的函数。

    你会有这个:

    test('test my function', () async {
      await function(x, y);
    });
    

    好的,但是我如何测试函数是否被调用?

    为此,您可以使用 mockito 这是一个用于测试目的的模拟包。

    假设你的 x/y 类是:

    class DoSomething {
      Future<Object> doSomethingAsync() async {}
      void doSomething() {}
    }
    

    然后您可以通过使用以下方法模拟您的类方法来使用 Mockito:

    // Mock class
    class MockDoSomething extends Mock implements DoSomething {
    }
    

    最后,您可以通过以下方式在测试中使用该模拟:

    test('test my function', () async {
      final x = new MockDoSomething();
      final y = new MockDoSomething();
      // test return != null
      when(x.doSomethingAsync()).thenReturn(42);
      await function(x, y);
    
      verifyNever(x.doSomething());
      verify(x.doSomethingAsync()).called(1);
      // y.doSomething must not be called since x.doSomethingAsync returns 42
      verify(y.doSomething()).called(1);
      verifyNever(y.doSomethingAsync());
    
      // reset mock
      clearInteractions(x);
      clearInteractions(y);
    
      // test return == null
      when(x.doSomethingAsync()).thenReturn(null);
      await function(x, y);
    
      verifyNever(x.doSomething());
      verify(x.doSomethingAsync()).called(1);
      // y must not be called this x.doSomethingAsync returns null here
      verifyZeroInteractions(y);
    });
    

    【讨论】:

    • 嘿,谢谢你的回答,但我的function 不是也不能是异步的。
    • 考虑到你的函数使用then,你的函数异步的
    • 哦,我明白了,我不知道我可以在函数上调用 await,即使我没有将它声明为 async。那么谢谢你的回答:)
    • 这与声明函数async 无关。 async 函数仅强制函数返回 Future&lt;whatever&gt;。虽然await 运算符不用于函数,但用于Future。如果你愿意,你可以等待一个变量,只要它是一个Future
    • 好的,如果我在 and is then 子句中嵌套了 not-async 函数,我该怎么办。如何测试顶级功能?
    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2014-02-08
    • 2015-04-25
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多