[英]Flutter test GraphQL query
我想测试我的 GraphQL 查询。 我有我的 GraphQL 客户端,我使用远程数据源来执行我的请求。
class MockGraphQLClient extends Mock implements GraphQLClient {}
void main() {
RemoteDataSource RemoteDataSource;
MockGraphQLClient mockClient;
setUp(() {
mockClient = MockGraphQLClient();
RemoteDataSource = RemoteDataSource(client: mockClient);
});
group('RemoteDataSource', () {
group('getDetails', () {
test(
'should preform a query with get details with id variable',
() async {
final id = "id";
when(
mockClient.query(
QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
),
),
).thenAnswer((_) async => QueryResult(
data: json.decode(fixture('details.json'))['data'])));
await RemoteDataSource.getDetailsQuery(id);
verify(mockClient.query(
QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
),
));
});
});
});
}
我想知道如何模拟查询的响应。 目前它不返回结果,它返回 null但我不明白为什么我的查询返回 null,虽然我嘲笑了我的客户,并且在我的“when”方法中我使用“thenAnwser”返回所需的值
final GraphQLClient client;
ChatroomRemoteDataSource({this.client});
@override
Future<Model> getDetails(String id) async {
try {
final result = await client.query(QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
)); // return => null ????
if (result.data == null) {
return [];
}
return result.data['details']
} on Exception catch (exception) {
throw ServerException();
}
}
when
应该模拟答案的论点非常复杂。 在测试用例中使用any
可能会更容易。
when(mockClient.query(any)).thenAnswer((_) async => QueryResult(
data: json.decode(fixture('details.json'))['data'])));
any
由 Mockito 提供以匹配任何参数。
在里面
graphql_flutter:^5.0.0
你需要添加源为 null 或 QueryResultSource.network,当调用方法时你可以传递任何所以你不需要传递QueryOptions( documentNode: gql(Queries.getDetailsQuery), variables: { 'id': id, }, )
,
这是最终代码: when(mockClient.query(any)).thenAnswer((_) async => QueryResult( data: json.decode(fixture('details.json'))['data'], ,source: null)));
any
不接受graphQLClient.query(any))
因为它接受不可为空QueryOptions<dynamic>
使用mockito: ^5.1.0
,您将收到警告: The argument type 'Null' can't be assigned to the parameter type 'QueryOptions<dynamic>'
我通过创建模拟的 QueryOptions 来解决它:
class SutQueryOption extends Mock implements QueryOptions {}
void main() {
SutQueryOption _mockedQueryOption;
....
setUp(() {
SutQueryOption _mockedQueryOption = MockedQueryOptions();
....
});
when(mockClient.query(_mockedQueryOption)).thenAnswer((_) async => ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.