'How to test getters in a state class using bloc_test?
Say I have a 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(
        '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.
Solution 1:[1]
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:
group('canProceed', () {
  group('when isSaving = false and errorMsg is empty', () {
    test('returns true', () {
      final state = MyState(isSaving: false, errorMsg: '');
      
      expect(state.canProceed, isTrue);
    });
  });
});
    					Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | mkobuolys | 
