flutter - Flutter 中 Mockito 缺少 stub 错误。尝试使用 Dio 的帖子

标签 flutter unit-testing mockito dio

我正在尝试使用 Dio 执行发布请求并使用 Mockito 进行测试。但不知道为什么会出现这个错误,有人知道这是什么吗?

测试错误:

User Profile Image should verify if post method is successfully called [E]          
  MissingStubError: 'post'
  No stub was found which matches the arguments of this method call:
  post('/CadastroUsuario/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b2a3b5b286a3bea7abb6aaa3e8a5a9ab" rel="noreferrer noopener nofollow">[email protected]</a>/salvarFotoPerfil', {data: Instance of 'FormData', queryParameters: null, options: null, cancelToken: null, onSendProgress: null, onReceiveProgress: null})
  
  Add a stub for this method using Mockito's 'when' API, or generate the mock for MockDio with 'returnNullOnMissingStub: true'.
  package:mockito/src/mock.dart 190:7                                 Mock._noSuchMethod
  package:mockito/src/mock.dart 184:45                                Mock.noSuchMethod
  test/data/c_user_registration_data_source_test.mocks.dart 147:14    MockDio.post
  package:app_test/data/c_user_registration_data_source.dart 70:33  CUserRegistrationDataSource.setUserProfileImage

我的测试代码:

group('User Profile Image', () {
    const email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7105140205311409101c011d145f121e1c" rel="noreferrer noopener nofollow">[email protected]</a>';

    var imagePath = File('test/assets/images/profile_image.png').path;
    var expectedUrl = uploadUserProfilePhotoPath.replaceFirst('{email}', email);

    test('should verify if post method is successfully called', () async {
      var formData = FormData.fromMap({
        'profileImage': await MultipartFile.fromFile(imagePath),
      });

      when(dio.post(
        expectedUrl,
        data: formData,
      )).thenAnswer(
        (_) async => Response(
          data: null,
          statusCode: 200,
          requestOptions: CommomMocks.getRequestOptions(expectedUrl),
        ),
      );

      await dataSource.setUserProfileImage(
        email: email,
        imagePath: imagePath,
      );

      verify(dio.post(expectedUrl, data: formData)).called(1);
    });
  });

实现:

@override
  Future<void> setUserProfileImage({
    required String email,
    required String imagePath,
  }) async {
    final http = _httpClientApp.instance();

    var apiUrl = uploadUserProfilePhotoPath.replaceFirst('{email}', email);
    var formData = FormData.fromMap({
      'profileImage': await MultipartFile.fromFile(imagePath),
    });

    final response = await http.post(apiUrl, data: formData);
    return _handleResponse(response);
  }

它表明模拟 Dio 中的方法 post 丢失。我已经运行 pub 命令来生成模拟,并在调用实现方法之前创建 stub 。我有什么遗漏的吗?

提前致谢。

最佳答案

我认为问题出在 prod 函数中的“FormData”实例中:

var formData = FormData.fromMap({
    'profileImage': await MultipartFile.fromFile(imagePath),
});

每次测试运行时,都会创建一个新实例,并且 stub 不一样。

所以我找到的解决方案是使用类型匹配器来检查该函数是否调用了“FormData”类型的任何参数。

 test('should verify if post method is successful called', () async {
    httpStubs.setUpMockHttpClientAppSuccess(expectedUrl, formData);

    await dataSource.setUserProfileImage(
      email: email,
      imagePath: imagePath,
    );

    verify(
      () => httpClientApp.post(
        expectedUrl,
        body: isA<FormData>(),
      ),
    ).called(1);
  });

stub 函数:

void setUpMockHttpClientAppSuccess(String url, dynamic payload) {
when(
  () => httpClientApp.post(
    any(),
    body: any(named: 'body'),
  ),
).thenAnswer(
  (_) async => Response(
    data: null,
    statusCode: 200,
    requestOptions: CommomMocks.getRequestOptions(url),
  ),
);

}

我不确定该解决方案是否是最佳解决方案或最佳实践,因此这解决了我的测试问题。如果有人知道更好的解决方案,请告诉我。

谢谢大家!! :)

关于flutter - Flutter 中 Mockito 缺少 stub 错误。尝试使用 Dio 的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70461029/

相关文章:

flutter - 更改时存储列表变量

dart - flutter : how to use focusNode property on TextField

list - ListView 使用Flutter中的属性过滤掉最后一行数据

ruby-on-rails - 使用特定的 RAILS_ENV 进行单个单元测试

java - 如何在 powermock 中模拟 void 方法

java - 为什么我在模拟 TextView 时会收到 InvalidUseOfMatchersException?

scala - 无法在 Scala 中使用 Mockito ArgumentMatchers

flutter - 在静态方法中传递 BuildContext 会导致 Flutter 中的内存泄漏吗?

swift - 快速测试是否支持泛型?

java - 使用构造函数参数模拟类