我有一个测试文件,用于测试间接调用computeVoucher
方法的addToCart
方法。computeVoucher
方法对GraphQL客户端进行API调用,为了测试的目的,对其进行模拟。实际查询和模拟查询的参数匹配,但是没有调用thenAnswer
方法。mock是使用Mockito生成的。
代码如下:
test.dart
test('When only voucher is added and exceeds cart total', () async {
final Cart cart = Cart();
cart.voucher = Voucher('test12345', true, 'Flat', 250, 1, 250,
client: mockClient, id: '12345');
await cart.addToCart(product);
expect(cart.pricingSummary.totalAmount, 0.0);
});
voucher.dart
Future<int?> computeVoucher(
String? voucherId, List cartProducts) async {
Map<String, dynamic> variables = {
'voucherId': voucherXid,
'cartProducts': CartProduct.getProducts(false, cartProducts),
'cartLineItems': CartProduct.getProducts(true, cartProducts)
};
Map<String, dynamic> result = await (client!
.query(query: computeVoucherQuery, variables: variables));
return result['computeVoucherDiscount'].toInt();
}
voucher_mock.dart
Future query(
{required String query, var variables, bool networkOnly = true}) async {
when(_client.query(QueryOptions(
document: gql(computeVoucher['query']),
variables: computeVoucherVariables,
fetchPolicy: FetchPolicy.networkOnly)))
.thenAnswer((realInvocation) async =>
MockQueryResult(data: computeVoucher['response']));
}
错误信息是:" error: Null is not a type of Future"
如果你想从方法存根返回一个Future或Stream,使用thenAnswer。
使用
thenReturn
返回Future
或Stream
将抛出ArgumentError
。这是因为它可能导致意想不到的行为。…
相反,使用
thenAnswer
来存根返回Future
或Stream
的方法。
您可以尝试使用thenReturn
代替预期,不能是Future或Stream,由于区域的考虑。