如何测试Flutter中抛出的函数

21 阅读1分钟

当为抛出的函数编写测试期望时,我们需要有点小心。

例如,考虑这个简单的测试。

test('function throws', () {
  expect(
    someFunctionThatThrows(),
    throwsStateError,
  );
});

在这种情况下,测试将失败,因为someFunctionThatThrows() 调用expect 函数之前就被评估了。

这相当于把测试写成这样。

test('function throws', () {
  // if the function throws, the test will fail immediately
  final result = someFunctionThatThrows();
  // and this line will never be exectuted
  expect(
    result,
    throwsStateError,
  );
});

为了解决这个问题,我们可以传递一个匿名函数作为参数给期望方法。

test('function throws', () {
  expect(
    // function argument, will be evaluated *inside* the expect function
    () => someFunctionThatThrows(),
    throwsStateError,
  );
});

或者更好的是,我们可以使用拆分,直接将someFunctionThatThrows 作为参数传递**(不调用它**)。

test('function throws', () {
  expect(
    someFunctionThatThrows,
    throwsStateError,
  );
});

这样做更安全,也更简洁。👌

关于拆分的更多信息,请看这个关于有效使用Dart的规则

编码愉快!