即使实际查询和模拟查询的参数匹配,也不会调用 thenAnswer方法



我有一个测试文件,用于测试间接调用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返回FutureStream将抛出ArgumentError这是因为它可能导致意想不到的行为。

相反,使用thenAnswer来存根返回FutureStream的方法。

您可以尝试使用thenReturn代替预期,不能是Future或Stream,由于区域的考虑。