0

我有一个类,它将imgUrl在构造函数中获取第一次创建。而且我需要编写一个测试来确保调用实例的get方法。Dio但是,我遇到了 fetch 结果返回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)

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

4

1 回答 1

1

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

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

干杯。

于 2020-02-04T08:47:12.133 回答