Reputation: 197
I'm trying to unit test using the given code.
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')));
});
My unit test includes a predicate throwsA((f) => f.toString().contains('employeeName: Must at least be 5 characters long'))
as given but dart fails this test with the exception:
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.
So what's the correct way to write this test in Dart?
Upvotes: 0
Views: 564
Reputation: 71683
Try removing the await
, or move it outside/before the expectLater
.
The only difference between expect
and expectLater
is that the latter returns a future, but you ignore that future.
The expect
/throwsA
needs either a closure or a Future
as the actual value, but you await
that future so the await ...
expression throws before you even call expectLater
. Remove the await
so you pass the Future
to expectLater
and the throwsA
will then catch and match the error of that future.
So, I recommend changing it to:
await expectLater(employeesDB.createEmployee(employee), ...
Upvotes: 1