Used on a non-mocktail object
package:matcher fail
package:mocktail/src/mocktail.dart 522:7 _makeVerify.<fn>
test\features\auth\data\datasources\remote_data_source_test.dart 69:15 main.<fn>.<fn>.<fn>
使用 Mocktail 验证功能我试图验证我的测试功能发布的数据是否与 Mocktail 创建的模拟 Dio 发布的数据相同。 此验证包括应由 dio(即 MultipartFile)发布的异步数据。 如果没有这个 MultipartFile,我的代码可以正常工作,并且可以按预期进行验证。
但是当我尝试使用 MultipartFile 进行验证时,它会抛出此错误,因为我已将验证函数设为异步。
test("It should post loginUser and return void by calling only once", () {
//Arrange
when(() => dio.post(
any(),
data: any(named: "data"),
))
.thenAnswer((invocation) async => Response(
requestOptions: RequestOptions(),
statusCode: 201,
data: {"message": "user logged in sucessfully"}));
//Act
final response = remoteDatasource.loginUser(
name: params.name,
phoneNumber: params.phoneNumber,
countryCode: params.countryCode,
image: params.image);
//Assert
expect(response, completes);
verify(() async => dio.post(dio.options.baseUrl + loginUrl,
data: FormData.fromMap({
"image": params.image != null
? await MultipartFile.fromFile(params.image!.path,
filename: imageFileName)
: null,
"name": params.name,
"phoneNumber": params.phoneNumber,
"countryCode": params.countryCode
}))).called(1);
verifyNoMoreInteractions(dio);
});
当我不使用异步时,它会抛出此错误:
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:matcher fail
package:mocktail/src/mocktail.dart 728:7 _VerifyCall._checkWith
package:mocktail/src/mocktail.dart 519:18 _makeVerify.<fn>
test\features\auth\data\datasources\remote_data_source_test.dart 69:15 main.<fn>.<fn>.<fn>
它肯定不会验证,因为现在 MultipartFile 将作为 Future 并且在我的实际函数中存在等待,即:
Future<void> loginUser(
{required String name,
required int phoneNumber,
required String countryCode,
File? image}) async {
try {
final String url = _dio.options.baseUrl + loginUrl;
final MapData data = {
'image': image != null
? await MultipartFile.fromFile(
image.path,
filename: imageFileName,
)
: null,
"name": name,
"phoneNumber": phoneNumber,
"countryCode": countryCode
};
final response = await _dio.post(
url,
data: FormData.fromMap(data),
);
print(url.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
return;
} else {
throw ApiException(
message: response.data.message,
statusCode: response.data.statusCode);
}
} on DioException catch (dioException) {
throw ApiException(
message: dioException.error.toString(), statusCode: 500);
} catch (e) {
throw ApiException(message: e.toString(), statusCode: 500);
}
}
注意:当图像不存在时,params 和 dio 工作正常。
您可以采取一些措施来解决这个问题,因为我今天自己偶然发现了这个问题,所以当我使用对函数参数不明确的数据类型时,我会收到错误,这是我们正在讨论的示例 这是声明的函数是 localDataSource 类
function cacheBooksData(String url,List<Book> books)
当我验证时,我使用返回 getBooks
的结果,所以这个结果我将其传递给导致错误的 Either<Failure,List<Book>>
,所以在调用函数时我没有这样做,而是创建了变量 ExpectedResultToCache类型为 cacheBookData(CACHE_BOOK_KEY,Right(result))
,然后在调用 verify 时传递它。好吧,长话短说:
要解决您的问题,请创建由 dio 发送的变量
List<Book>
,然后在调用验证时使用该变量,并删除验证中的
expectedFormData
键工作,因为该变量将具有实际数据