我正在尝试对功能进行单元测试。这是生产代码:
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
_responseRestaurantsModel =
ResponseRestaurantsModel.fromJson(jsonResponse);
if (_responseRestaurantsModel.documents.isEmpty)
throw NoResultFoundException();
return _responseRestaurantsModel;
} else {
throw ServerException();
}
这里_responseRestaurantsModel.documents
是List
,如果它为空,则抛出异常。
这是测试代码:
class MockResponseRestaurantModel extends Mock implements ResponseRestaurantsModel {}
setUp(() {
mockHttpClient = MockHttpClient();
dataSource = RestaurantRemoteDataSourceImpl(mockHttpClient);
tResponseRestaurantModel = MockResponseRestaurantModel();
});
test(
'should throw NoResultFoundException when the list is empty',
() async {
// arrange
when(tResponseRestaurantModel.documents.isEmpty).thenReturn(null);
// act
final call = dataSource.getRestaurants;
// assert
expect(
() => call(params....), throwsA(TypeMatcher<NoResultFoundException>()),
);
},
);
但是测试失败,显示错误:NoSuchMethodError:在空方法上调用了吸气剂'isEmpty'。这是怎么回事?
class ResponseRestaurantsModel {
List<RestaurantModel> documents;
MetaRestaurantsModel meta;
ResponseRestaurantsModel({@required this.documents, @required this.meta});
ResponseRestaurantsModel.fromJson(Map<String, dynamic> json) {
if (json['documents'] != null) {
documents = new List<RestaurantModel>();
json['documents'].forEach((v) {
documents.add(new RestaurantModel.fromJson(v));
});
}
meta = json['meta'] != null
? new MetaRestaurantsModel.fromJson(json['meta'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.documents != null) {
data['documents'] = this.documents.map((v) => v.toJson()).toList();
}
if (this.meta != null) {
data['meta'] = this.meta.toJson();
}
return data;
}
}
模型类:
答案 0 :(得分:1)
tResponseRestaurantModel.documents
为空,因此您必须将此属性添加到MockResponseRestaurantModel
答案 1 :(得分:0)
将代码更改为此:
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
_responseRestaurantsModel =
ResponseRestaurantsModel.fromJson(jsonResponse);
if (_responseRestaurantsModel?.documents?.isEmpty ?? true)
throw NoResultFoundException();
return _responseRestaurantsModel;
} else {
throw ServerException();
}