我正在尝试实现我的“AuthenticationRemoteDataSource”,并且我正在编写测试。就像测试驱动开发一样。
此实现是与 API 通信的最新层。我有两个用例:“createUser”和“getUsers”。我已经为 createUser 编写了测试并且它们正在通过。无论是成功状态还是不成功状态。 我也通过了getUsers的成功状态,但是在不成功的测试中找不到错误,失败了。
这是我在“AuthenticationRemoteDataSourceImplementation”类中的 getUsers 实现:
Future<List<UserModel>> getUsers() async {
try {
final response =
await _client.get(Uri.parse('$kBaseUrl$kGetUsersEndpoint'));
if (response.statusCode != 200) {
throw (
APIException(
message: response.body,
statusCode: response.statusCode,
),
);
}
return List<DataMap>.from(jsonDecode(response.body) as List)
.map((userdata) => UserModel.fromMap(userdata))
.toList();
} on APIException {
rethrow;
} catch (e) {
throw APIException(message: e.toString(), statusCode: 505);
}
}
“DataMap”基本上就是 Map
并且,这是我从测试文件中进行的 getUsers 测试:
group('getUsers', () {
const testList = [UserModel.empty()];
test('Should return a [List<UserModel>] when the status code is 200',
() async {
// stubbing
when(
() => client.get(
any(),
),
).thenAnswer((_) async =>
http.Response(jsonEncode([testList.first.toMap()]), 200));
// act
final result = await remoteDataSource.getUsers();
// assert
expect(result, equals(testList));
verify(() => client.get(Uri.parse('$kBaseUrl$kGetUsersEndpoint')))
.called(1);
verifyNoMoreInteractions(client);
});
// THIS IS THE FAILING TEST
test('Should throw an [APIException] when the status code is not 200',
() async {
// stubbing
when(() => client.get(any())).thenAnswer(
(_) async => http.Response(
'Server is down',
505,
),
);
// act
final methodCall = remoteDataSource.getUsers;
// assert
expect(
() => methodCall(),
throwsA(
const APIException(
message: 'Server is down',
statusCode: 505,
),
),
);
verify(
() => client.get(
Uri.parse('$kBaseUrl$kGetUsersEndpoint'),
),
).called(1);
verifyNoMoreInteractions(client);
});
});
我得到的错误:
Expected: throws APIException:<APIException(Server is down, 505)>
Actual: <Closure: () => Future<List<UserModel>>>
Which: threw APIException:<APIException((APIException(Server is down, 505)), 505)>
stack package:cleanarchtdd/src/authentication/data/datasources/authentication_remote_data_source.dart 78:7 AuthenticationRemoteDataSourceImplementation.getUsers
===== asynchronous gap ===========================
package:matcher expect
package:flutter_test/src/widget_tester.dart 454:18 expect
test\src\authentication\data\datasources\authentication_remote_data_source_test.dart 147:7 main.<fn>.<fn>
package:matcher expect
package:flutter_test/src/widget_tester.dart 454:18 expect
test\src\authentication\data\datasources\authentication_remote_data_source_test.dart 147:7 main.<fn>.<fn>
我尝试在 while 和 verify 方法中使用 async 关键字,但它们导致了不同的错误。我写的测试类似于“createUser”不成功状态。
我发现了这个错误。我在实现中写了
throw( APIException() )
。我应该写,throw APIException()
。显然没有括号。