首页 > 解决方案 > Dart 单元测试框架的 `expect` 似乎无法正常工作

问题描述

这是要比较的对象的 de MapState

class MapState {
  final Coordinate currentCoordinate;
  final Iterable<Coordinate> markers;

  MapState(this.currentCoordinate, this.markers);

  MapState.empty()
      : this.currentCoordinate = null,
        this.markers = [];

  MapState.withCoordinate(this.currentCoordinate) : this.markers = [];

  MapState.withMarkers(this.markers) : this.currentCoordinate = null;

  MapState newCoordinate(final Coordinate coordinate) =>
      MapState(coordinate, this.markers);

  MapState newMarkersSet(final Iterable<Coordinate> markers) =>
      MapState(this.currentCoordinate, markers);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is MapState &&
              runtimeType == other.runtimeType &&
              currentCoordinate == other.currentCoordinate &&
              markers == other.markers;

  @override
  int get hashCode =>
      currentCoordinate.hashCode ^
      markers.hashCode;

}

这是单元测试:

test('init, Observer should receive an empty state as a first state',
  () {
    expect(MapState.empty(), MapState.empty());
  });

结果(当然是失败):

预期:“MapState”的实例

实际:“MapState”的实例

包:test_api 期望

包:flutter_test/src/widget_tester.dart 196:3 期望

测试/应用程序/map_bloc_test.dart 25:5 主要。

我将原始测试简化为跟踪错误,所以不要对单元测试的无意义感到困惑。

更改expect(MapState.empty(), MapState.empty());为有expect(1, 1);帮助,但我无法让它与我的对象一起使用。

另外,这是我的导入块:

import 'dart:async';

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:taxi/application/map_bloc.dart';
import 'package:taxi/domain/map.dart';

PS:奇怪的是,但更改this.markers = []为有this.markers = const []帮助。呜???无论如何,expect([], []);工作。这对我来说没有任何意义。

标签: unit-testingdart

解决方案


测试失败是因为[] == []falseDart 中。您可以使用集合包来处理集合相等性。


推荐阅读