颤振测试GraphQL查询



我想测试我的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,虽然我嘲笑了我的客户,并在我的"当"方法,我使用了" thenanswer "返回所需值

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)));

graphQLClient.query(any))不接受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 => ....

最新更新