如何简化匹配器

时间:2014-07-08 15:12:27

标签: unit-testing dart

我已经实现了我自己的Matcher来测试List<List<T>>中的每个元素的长度为0.测试看起来有点冗长,我想知道是否有办法简化它。

void main() {   
  Board board = new Board(10,10); // board.pieces is a List<List<Piece>>
  test('All pieces have a length of 0', () => expect(board.pieces,everyElement(length) ));
}

class LengthMatcher extends Matcher {
  final int _length;
  LengthMatcher(this._length);
  bool matches(item, Map matchState) => item is List && item.length==_length;

  Description describe(Description description) =>  description.add('A List with a length of $_length');
}
LengthMatcher length = new LengthMatcher(0);

1 个答案:

答案 0 :(得分:1)

everyElement的参数名为matcher,但没有类型,因此为dynamic
支持的是匹配器和函数。

import 'package:unittest/unittest.dart';
import 'package:matcher/matcher.dart';

void main(args) {
  List<List<int>> board = [[],[],[],[],[],[],[],[],[],[]];

  test('', () {
    expect(board, everyElement((List e) => e is List && e.length == 0));
  });
}