简体   繁体   English

Flutter 测试模拟 GraphQL 突变未找到存根

[英]Flutter Test Mock GraphQL mutation doesn't find stub

I'm using mockito and graphql packages in my flutter app in order to write tests for my graphql mutations without it actually doing a database read.我在我的 flutter 应用程序中使用 mockito 和 graphql 包,以便为我的 Z572CDA51902B55017C0E1A2B2 数据库编写测试而不实际执行 aFDB04B4Z 突变。 The way Mockito works is that i set a "when" clause which makes it so whenever that particular method is called on my mocker it uses what I defined instead of what would run normally. Mockito 的工作方式是我设置了一个“when”子句,这样每当在我的 mocker 上调用该特定方法时,它就会使用我定义的方法而不是正常运行的方法。

I've defined a when for my mocked GraphQLClient for client.mutate().我已经为 client.mutate() 的模拟 GraphQLClient 定义了何时。 however, when I call mutate it says that there is no mock defined.但是,当我调用 mutate 时,它说没有定义模拟。 I've done research online and several people fixed the issue by making sure they define the when first, which I have done, but it still hasn't solved my issue.我已经在网上进行了研究,并且有几个人通过确保他们定义了何时首先解决了这个问题,我已经这样做了,但它仍然没有解决我的问题。 Here is my initialization and packages这是我的初始化和包

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

and the client and mutation和客户和突变

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

and now the test case现在是测试用例

  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(''));
  });

Make sure the mocks file is generated.确保生成了模拟文件。 The file name should be something like that: 'your_test_file_name.mocks.dart'文件名应该是这样的:'your_test_file_name.mocks.dart'

if you can't find the generated mocks file try running如果找不到生成的模拟文件,请尝试运行

flutter pub run build_runner build

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM