Dart/Flutter 中的单元测试异常

Unit Testing Exceptions in Dart/Flutter

我正在尝试使用给定的代码进行单元测试。

test('Given Employee When employeeName less than 5 then throws Exception', () async {
    final employee = EmployeesCompanion.insert(
        employeeName: 'Tony',
        employeeCode: 'HR-121',
        address: '5th Floor, Park Avenue',
        contact: '1234567890',
        hiringDate: DateTime.now());
    expectLater(await employeesDB.createEmployee(employee),
        throwsA((f) => f.toString().contains('employeeName: Must at least be 5 characters long')));
  });

我的单元测试包括给定的谓词 throwsA((f) => f.toString().contains('employeeName: Must at least be 5 characters long')),但 dart 未能通过此测试,但例外情况是:

package:moor/src/runtime/data_verification.dart 74:5                  VerificationContext.throwIfInvalid
package:moor/src/runtime/query_builder/statements/insert.dart 197:51  InsertStatement._validateIntegrity
package:moor/src/runtime/query_builder/statements/insert.dart 96:5    InsertStatement.createContext
package:moor/src/runtime/query_builder/statements/insert.dart 64:17   InsertStatement.insert
package:moor_ex/src/db/employees.dart 79:76                           EmployeesDB.createEmployee
test\employee_dept_test.dart 28:35                                    main.<fn>

InvalidDataException: Sorry, EmployeesCompanion(id: Value.absent(), employeeName: Value(Tony), employeeCode: Value(HR-121), address: Value(5th Floor, Park Avenue), contact: Value(1234567890), hiringDate: Value(2020-08-18 13:26:34.435349)) cannot be used for that because: 
• employeeName: Must at least be 5 characters long.

那么在 Dart 中编写这个测试的正确方法是什么?

尝试删除 await,或将其移动 outside/before expectLater

expectexpectLater的唯一区别是后者returns一个未来,而你忽略那个未来。

expect/throwsA 需要闭包或 Future 作为实际值,但你 await 那个 future 所以 await ... 表达式在你调用 expectLater 之前抛出。删除 await,以便将 Future 传递给 expectLater,然后 throwsA 将捕获并匹配该未来的错误。

因此,我建议将其更改为:

  await expectLater(employeesDB.createEmployee(employee), ...