這是我試圖為其撰寫測驗的一種方法。我只想撰寫一個非常簡單的測驗來驗證它是否send()被呼叫。但主要的麻煩制造者是實體MultipartRequest。如您所見,我直接使用MultipartRequest實體,而不是作為依賴項。所以,我不認為我應該把它存根。我可以輕松地存根getCachedToken()方法作為一個實體TokenValueLocalDataSource作為依賴項傳入。你認為我應該怎么做才能得到我想要的測驗結果?
Future<Unit> addPost({
File? imageFile,
String? bodyText,
}) async {
if (imageFile != null || bodyText != null) {
final tokenModel = await tokenValueLocalDataSource.getCachedToken();
final stringUrl = EnvValues.addPostUrl;
final request = http.MultipartRequest(
'POST',
Uri.parse(stringUrl),
)..headers.addAll(
{
'Authorization': 'Token ${tokenModel.token}',
},
);
if (bodyText != null) {
request.fields['body'] = bodyText;
}
if (imageFile != null) {
request.files.add(
await http.MultipartFile.fromPath('image', imageFile.path),
);
}
final response = await request.send(); // This needs to verified.
if (response.statusCode == 200) {
return unit;
} else {
throw ServerException();
}
} else {
throw InvalidRequestException(
"Both imageFile and bodyText can't be null",
);
}
}
uj5u.com熱心網友回復:
假設您正在使用該http軟體包,這是我的答案:
由于方法本身實體化MultipartRequest并從中呼叫方法,因此使代碼難以/不可能測驗。所以使用Client類更容易。那是一個抽象類,它做同樣的事情并且可以被模擬。經過幾次重構,您可以看到以下示例:
class ApiClass {
final http.Client _client;
const ApiClass(this._client);
Future<Unit> addPost({File? imageFile, String? bodyText}) async {
if (imageFile != null || bodyText != null) {
final tokenModel = await tokenValueLocalDataSource.getCachedToken();
final stringUrl = EnvValues.addPostUrl;
final request = http.MultipartRequest(
'POST',
Uri.parse(stringUrl),
)..headers.addAll(
{
'Authorization': 'Token ${tokenModel.token}',
},
);
if (bodyText != null) {
request.fields['body'] = bodyText;
}
if (imageFile != null) {
request.files.add(
await http.MultipartFile.fromPath('image', imageFile.path),
);
}
final response = await _client.send(request);
if (response.statusCode == 200) {
return unit;
} else {
throw ServerException();
}
} else {
throw InvalidRequestException(
"Both imageFile and bodyText can't be null",
);
}
}
}
測驗將是這樣的:
void main() {
group('ApiClass', () {
late ApiClass apiClass;
late http.Client client;
setUp(() {
client = _MockClient();
apiClass = ApiClass(client);
registerFallbackValue(_FakeMultipartRequest());
});
test('your test description', () async {
final response = _MockStreamedResponse();
when(() => response.statusCode).thenReturn(200);
when(
() => client.send(any(
that: isA<http.MultipartRequest>()
.having((p0) => p0.files.length, 'has all files', 1))),
).thenAnswer((_) async => response);
final result = await apiClass.addPost(bodyText: 'some text');
expect(result, equals(unit));
});
});
}
class _MockStreamedResponse extends Mock implements StreamedResponse {}
class _FakeMultipartRequest extends Fake implements MultipartRequest {}
class _MockClient extends Mock implements Client {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/406801.html
標籤:
