Flutter 测试 GraphQL 查询

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

我想知道如何模拟查询的响应。目前它没有 return 结果,它 return 为 null 但是我不明白为什么我的查询 return 为空,尽管我嘲笑了我的客户,并且在我的“when”方法中我使用“thenAnwser”来 return 所需的值

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,当调用方法 when 时,您可以传递 any 吗?不需要通过 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 => ....