在 Dart 中测试包含异步函数的函数

Testing function containing async function in Dart

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

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

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

您可以在 dart 中使用 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 是:

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

然后您可以通过以下方式模拟您的 class 方法来使用 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);
});