飞镖/颤振中的单元测试异常

问题描述

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

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,或将其移到expectLater之前/之前。

expectexpectLater之间的唯一区别是后者返回了未来,但是您忽略了该未来。

expect / throwsA需要使用闭包或Future作为实际值,但是您await拥有这样的未来,因此await ...表达式会在之前您甚至可以致电expectLater。删除await,以便将Future传递给expectLater,然后throwsA将捕获并匹配该将来的错误。

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...