我正在使用mocktail進行單元測驗,但我找不到在第一次呼叫時拋出例外的方法,但后來在第二次呼叫中,以正確的輸出回答。
我可以為兩個不同的答案找到這個解決方案,但這不足以測驗拋出的例外。所以我需要想出一個修改過的解決方案。
這就是我想要達到的目標。順便說一下,我正在使用 http get 測驗連接重試。
import 'package:http/http.dart' as http;
import 'package:mocktail/mocktail.dart';
class MockClient extends Mock implements http.Client {}
final mockClient = MockClient();
//First time fails, second one retrieves a result. This doesn't work on Mocktail
when(() => mockClient.get(Uri.parse(url)))
.thenThrow(SocketException()) // Call 1
.thenAnswer((_) => Future.value(http.Response("page content", 200)) // Call 2
);
uj5u.com熱心網友回復:
在嘗試了不同的想法之后,一個可能的解決方案是將每個答案存盤在一個 List
import 'package:http/http.dart' as http;
import 'package:mocktail/mocktail.dart';
class MockClient extends Mock implements http.Client {}
final mockClient = MockClient();
final List<Future<http.Response> Function(Invocation)> answers = [
(_) => throw SocketException(),
(_) => Future.value(http.Response("page content", 200)),
];
when(() => mockClient.get(Uri.parse(url)))
.thenAnswer((invocation) => answers.removeAt(0)(invocation));
// Calling answers.removeAt(0) without the lambda method returns the same answer on all of them
在這個例子Invocation中沒有使用并且只檢查 2 個連續的呼叫。但是這種行為可以從你在這里看到的擴展。
我還沒有用 Mockito嘗試過這個,但它應該以類似的方式適應語法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334709.html
