【问题标题】:How to write test for construction of a class using Dio?如何使用 Dio 编写构建类的测试?
【发布时间】:2025-12-06 20:55:01
【问题描述】:

我有一个类,它将在构造函数中第一次创建时获取imgUrl。 而且我需要编写一个测试来确保调用Dio 实例的get 方法。 但是,获取结果返回null 而不是Future 让我无法调用then


班级:

@JsonSerializable()
class DogBreed with ChangeNotifier {
  @JsonKey(ignore: true)
  final Dio dio;

  final String id;
  final String bred_for;
  final String breed_group;
  final String life_span;
  final String name;
  final String origin;
  final String temperament;
  final String description;
  final Measurement height;
  final Measurement weight;

  var imgUrl = '';

  DogBreed({
    this.dio,
    this.id,
    this.bred_for,
    this.breed_group,
    this.life_span,
    this.name,
    this.origin,
    this.temperament,
    this.description,
    this.height,
    this.weight,
  }) {
    dio.get(
      'xxxxx,
      queryParameters: {
        'breed_id': id,
        'limit': 1,
      },
    ).then((result) {
      final List data = result.data;

      if (result.statusCode == 200) {
        if (data.isNotEmpty) {
          imgUrl = result.data[0]['url'];
        } else {
          imgUrl = NO_IMAGE_AVAILABLE_URL;
        }
        notifyListeners();
      }
    });
  }

  factory DogBreed.fromJson(Map<String, dynamic> json) =>
      _$DogBreedFromJson(json);
}

我的测试:

class MockDio extends Mock implements Dio {}

void main() {
  MockDio mockDio;

  setUp(() {
    mockDio = MockDio();
  });

  test(
    "fetch the imageUrl on constructor",
    () async {
      when(mockDio.get(any))
          .thenAnswer((_) async => Response(data: 'url', statusCode: 200));

      final newBreedProvider = DogBreed(
        dio: mockDio,
        id: '12',
      );

      verify(mockDio.get(
        'xxxx',
        queryParameters: {
          'breed_id': 12,
          'limit': 1,
        },
      ));
    },
  );
}

运行测试结果:

dart:core                                                           Object.noSuchMethod
package:practises/projects/dog_facts/providers/dog_breed.dart 46:7  new DogBreed
test/projects/dog_facts/providers/dog_breed_test.dart 24:32         main.<fn>

NoSuchMethodError: The method 'then' was called on null.
Receiver: null
Tried calling: then<Null>(Closure: (Response<dynamic>) => Null)

谁能帮我弄清楚如何编写这个测试或建议我一种新的实现方式,以便我可以在这个测试上编写一个测试?

【问题讨论】:

标签: flutter mockito flutter-test dio


【解决方案1】:

我知道为什么,我需要在测试中为get 方法提供queryParameters 是我的错误。应该是:

      when(
        mockPdio.get(
          any,
          queryParameters: anyNamed('queryParameters'),
        ),
      ).thenAnswer((_) async => Response(data: 'url', statusCode: 200));

干杯。

【讨论】:

    最近更新 更多