我有以下設定:
class Resource<T> {
T? data;
String? error;
Resource._({this.data, this.error});
factory Resource.success(T? data) => Resource._(data: data);
factory Resource.error(String error) => Resource._(error: error);
factory Resource.loading() => Resource._();
}
class CategoriesRepo{
Stream<Resource<List<Category>>> getAllCategories() async* {
yield Resource.loading();
yield (Resource.error(NetworkErrors.NO_INTERNET));
}
}
test('Loading then error',
() async {
final categoriesRepo = CategoriesRepo();
expect(
categoriesRepo.getAllCategories(),
emitsInOrder([
Resource<List<Category>>.loading(),
Resource<List<Category>>.error(""),
]));
});
我收到此錯誤:
test\unit-tests\screens\categories\categories_repo_test_test.dart main.<fn>.<fn>
Expected: should emit an event that <Instance of 'Resource<List<Category>>'>
Actual: <Instance of '_ControllerStream<Resource<List<Category>>>'>
Which: emitted * Instance of 'Resource<List<Category>>'
* Instance of 'Resource<List<Category>>'
x Stream closed.
如何正確測驗上述流?
uj5u.com熱心網友回復:
測驗本身是有效的,但是在物件的斷言和比較方面存在一個小問題。基本上Resource.loading() == Resource.loading()是假的,所以斷言失敗。
為什么是假的?默認情況下,Dart 物件(除了基元)僅在它們是相同的實體時才相等。
為了使您的斷言和此類測驗有效,您需要==為您的物件實作operator 和 hashCode。您可以手動執行此操作,但這有點低效。很多人使用的軟體包equatable或凍結,equatable是更容易一點,因為它不涉及代碼生成和被推薦集團(基于流的狀態管理)的作者。
import 'package:equatable/equatable.dart';
class Resource<T> extends Equatable {
T? data;
String? error;
Resource._({this.data, this.error});
factory Resource.success(T? data) => Resource._(data: data);
factory Resource.error(String error) => Resource._(error: error);
factory Resource.loading() => Resource._();
@override
List<Object?> get props => [data, error];
}
當然,您也可以更改斷言,使其不再使用物件的比較,而是使用謂詞和匹配器,但這并不漂亮。
expect(
categoriesRepo.getAllCategories(),
emitsInOrder(
[
predicate<Resource<List<Category>>>(
(r) => r.error == null && r.data == null),
predicate<Resource<List<Category>>>(
(r) => r.error == "" && r.data == null),
],
),
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/343517.html
