lomsa-dev / http-mock-adapter

A simple to use mocking package for Dio intended to be used in tests.
https://pub.dev/packages/http_mock_adapter
MIT License
65 stars 42 forks source link

Data on onPost is compared before it's encoded to json #134

Open janosgy opened 2 years ago

janosgy commented 2 years ago

Description

According to my observation, the data field on dioAdapter.onPost is compared before it's encoded to json.

I use json_annotation, where some fields are configured not to be present if their value is null when encoded to json, but the tests are failing with "Could not find mocked route matching request for POST" and the data is shown with the null fields included + also instances have their types in the error message.

when I experimented with print(json.encode(originalData) == json.encode(expectationFromTest)); the result is true

Steps to reproduce

import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http_mock_adapter/http_mock_adapter.dart';

void main() {
  final dio = Dio(BaseOptions(baseUrl: 'http://localhost'));
  final dioAdapter = DioAdapter(dio: dio);

  test('should pass', () async {
    dioAdapter.onPost('/test', (server) => server.reply(201, {}), data: {
      "myObj": {"nested": true}
    });

    final payload = {"myObj": TestObj()};
    final response = await dio.post('/test', data: payload);

    expect(response.statusCode, 201);
  });
}

class TestObj {
  Map<String, dynamic> toJson() => {
        'nested': true,
      };
}

Produces this error:

DioError [DioErrorType.other]: Assertion failed: "Could not find mocked route matching request for POST /test { data: {myObj: Instance of 'TestObj'}, query parameters: {}, headers: {content-type: application/json; charset=utf-8, content-length: 25} }"

Expected behavior

Data from dio.post is encoded before comparing to dioAdapter's onPost data

System details

[✓] Flutter (Channel stable, 3.0.5, on macOS 12.3.1 21E258 darwin-arm, locale en-HU) [✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1) [✓] Xcode - develop for iOS and macOS (Xcode 13.2.1) [✓] Chrome - develop for the web [!] Android Studio (not installed) [✓] IntelliJ IDEA Ultimate Edition (version 2021.3.3) [✓] VS Code (version 1.64.1) [✓] Connected device (2 available) [✓] HTTP Host Availability

dio: ^4.0.4 http_mock_adapter: ^0.3.2

sebastianbuechler commented 1 year ago

Just as a comment: This has two pieces that break. One is the signature comparison of the request and the second is the actual body comparison.

The first breaks because we see for the actual request this signature "POST /test { data: {myObj: Instance of 'TestObj'}, query parameters: {}, headers: {content-type: application/json, content-length: 25} }" but it should be "POST /test { data: {myObj: {nested: true}}, query parameters: {}, headers: {} }".

The latter breaks because we have now a TestObj instance in the comparison and that is supposed to not match.