为什么Mockito Dart没有间谍功能



下面的代码是我的代码中的一个简化示例。我有一个依赖于类B的类A。我想测试类A,所以我模拟类B。然后我为类A的方法写一个测试,在这个测试中,每当调用模拟类B的方法时,我都会写一个存根:

fetchData() async {
try {
await b.getData();
}  on DioError catch (e) {
switch (e.response!.statusCode) {
case 401:
logout();
throw UnauthorizedException();
default:
throw UnspecifiedDioException(error: e);
}
}

为fetchData((方法编写的测试:

test('check if fetchData calls logout when 401 is returned', () {
when(mockB.getData())
.thenAnswer((_) async =>
throw DioError(
requestOptions: RequestOptions(path: ""),
response: Response(requestOptions: RequestOptions(path: ""), statusCode: 401)));
verify(a.logout()); // doesn't work because A isn't mocked
});

我读到过,你可以用间谍很容易地做到这一点,但令我惊讶的是,间谍适用于除飞镖外的所有使用mockito的语言。它显然被否决了,但话说回来,如果没有更新的版本来代替它,怎么会被否决呢。

如果有人能告诉我是否有一个方便的变通方法来实现我想要实现的目标,我将不胜感激。提前谢谢。

编辑:我改变了这个问题,因为前一个问题没有多大意义。我只是想知道飞镖里有没有间谍之类的东西。

使用mocktail您还应该截断logout调用的依赖关系。


class A {
A({required this.api, required this.auth});
// to be mocked
final Api api;
final Auth auth;
Future<void> fetchData() async {
try {
await api.getData();
} catch (e) {
auth.logout();
}
}
}
class Auth {
Future<void> logout() => Future(() {});
}
class Api {
Future<void> getData() => Future(() {});
}

和你的测试

class MockApi extends Mock implements Api {}
class MockAuth extends Mock implements Auth {}
void main() {
// create mock objects
final mockApi = MockApi();
final mockAuth = MockAuth();
test('when [Api.getData] throws, [Auth.logout] is called', () async {
// create an instance of "A" and use your mock objects
final a = A(api: mockApi, auth: mockAuth);
// use "thenThrow" to throw
when(() => mockApi.getData()).thenThrow('anything');
// use "thenAnswer" for future-returning methods
when(() => mockAuth.logout()).thenAnswer((_) => Future.value(null));
// call the method to "start" the test
await a.fetchData();
// verify logout was called
verify(mockAuth.logout).called(1); // passes
});
}

最新更新