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

问题描述 投票:0回答:1

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

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个回答
3
投票

你可以在飞镖中使用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);
});
© www.soinside.com 2019 - 2024. All rights reserved.