【发布时间】:2022-02-01 00:53:46
【问题描述】:
我在我的颤振应用程序中使用 mockito 和 graphql 包,以便为我的 graphql 突变编写测试,而无需它实际执行数据库读取。 Mockito 的工作方式是我设置了一个“when”子句,这样每当在我的 mocker 上调用该特定方法时,它就会使用我定义的方法而不是正常运行的方法。
我已经为 client.mutate() 的模拟 GraphQLClient 定义了一个 when。但是,当我调用 mutate 时,它说没有定义模拟。我已经在网上进行了研究,并且有几个人通过确保他们定义了何时首先解决了这个问题,我已经这样做了,但它仍然没有解决我的问题。这是我的初始化和包
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:graphql/client.dart' as graphql;
import 'login_screen_test.mocks.dart';
@GenerateMocks([graphql.GraphQLClient])
以及客户端和突变
final mockClient = MockGraphQLClient();
MutationOptions loginMutation = MutationOptions(
document: gql(
r'''
mutation Login($email: String!, $password: String!) {
login(input: {email:$email password:$password}) {
accessToken
refreshToken
user {
id
}
}
}
''',
),
variables: <String, dynamic>{
'email': 'doodle@noodle.com',
'password': 'password',
},
);
现在是测试用例
test('Login success if done correctly', () async {
when(mockClient.mutate(loginMutation)).thenAnswer((_) async => graphql.QueryResult(source: null, data: {'login': {'accessToken': 'ooglyboogly', 'refreshToken': 'mtnDew'}}));
await userRepo.loginEmailPassword(mockClient, email: 'doodle@noodle.com', password: 'password');
expect(store.state.auth.accessToken, isNot(''));
});
这是在 userRepo 中调用的突变
Future<bool> loginEmailPassword({required String email, required String password, mockClient = ''}) async {
final MutationOptions options = MutationOptions(
document: gql(
r'''
mutation Login($email: String!, $password: String!) {
login(input: {email:$email password:$password}) {
accessToken
refreshToken
user {
id
}
}
}
''',
),
variables: <String, dynamic>{
'email': email,
'password': password,
},
);
QueryResult result = mockClient == '' ? await client.mutate(options) : await mockClient.mutate(options);
if (result.hasException) {
throw Exception(result.exception);
}
store.dispatch(Login(accessToken: result.data!['login']['accessToken'],refreshToken: result.data!['login']['refreshToken']));
return true;
}
另一件事是我在生成的模拟文件中看到了 mutate 方法
@override
_i5.Future<_i2.QueryResult> mutate(_i2.MutationOptions? options) =>
(super.noSuchMethod(Invocation.method(#mutate, [options]),
returnValue: Future<_i2.QueryResult>.value(_FakeQueryResult_5()))
as _i5.Future<_i2.QueryResult>);
【问题讨论】:
标签: flutter unit-testing dart graphql mocking