简体   繁体   English

如何使用 bloc_test 测试 state class 中的吸气剂?

[英]How to test getters in a state class using bloc_test?

Say I have a state class假设我有一个 state class

class MyState extends Equatable {
  final bool isSaving;
  final String errorMsg;

  const MyState({
    this.isSaving = false,
    this.errorMsg = '',
  });

  @override
  List<Object?> get props => [
        isSaving,
        errorMsg,
      ];

  MyState copyWith({
    bool? isSaving,
    String? errorMsg,
  }) {
    return MyState(
      isSaving: isSaving ?? this.isSaving,
      errorMsg: errorMsg ?? this.errorMsg,
    );
  }

  bool get canProceed => !isSaving && errorMsg.isEmpty;
}

In my blocTest I could just do在我的blocTest我可以做

   blocTest(
        'canProceed is true',
        build: () => MyCubit(),
        act: (MyCubit c) => c.doSomething(),
        expect: () => [
          MyState(isSaving: false, errorMsg: ''),
        ],
      );

However I'd like to do something along the lines of但是我想做一些类似的事情

   blocTest(
        'canProceed is true',
        build: () => MyCubit(),
        act: (MyCubit c) => c.doSomething(),
        expect: (MyCubit c) => [c.canProceed],
      );

Is there a way to do this?有没有办法做到这一点? The first example gets tedious the more complex the getter becomes, especially when multiple states are emitted after doSomething() is called. getter 变得越复杂,第一个示例就越乏味,尤其是在调用doSomething()后发出多个状态时。

If you want to test a getter, you do not need to execute the test as a BLoC - just create a specific state instance and check what value is returned by the getter:如果你想测试一个 getter,你不需要作为 BLoC 执行测试 - 只需创建一个特定的 state 实例并检查 getter 返回的值:

group('canProceed', () {
  group('when isSaving = false and errorMsg is empty', () {
    test('returns true', () {
      final state = MyState(isSaving: false, errorMsg: '');
      
      expect(state.canProceed, isTrue);
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM