我正在尝试使用给定的代码进行单元测试。
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编写此测试的正确方法是什么?
答案 0 :(得分:1)
尝试删除await
,或将其移到expectLater
之前/之前。
expect
和expectLater
之间的唯一区别是后者返回了未来,但是您忽略了该未来。
expect
/ throwsA
需要使用闭包或Future
作为实际值,但是您await
拥有这样的未来,因此await ...
表达式会在之前您甚至可以致电expectLater
。删除await
,以便将Future
传递给expectLater
,然后throwsA
将捕获并匹配该将来的错误。
因此,我建议将其更改为:
await expectLater(employeesDB.createEmployee(employee), ...