Little Monkey
Little Monkey

Reputation: 6157

Testing the bloc state will pass even if some properties are not the same

This is mapEventToState of MyBloc:

@override
  Stream<MyBlocState> mapEventToState(MyBlocEvent event) async* {
    if (event is MyBlocInitialize) {
      yield MyBlocStateInitialized(event.something);
    }

where the states are defined like:

abstract class MyBlocState extends Equatable {
  EnterCredentialsState([List props = const []]) : super(props)
}

class MyBlocStateInitialized extends MyBlocState {
  final String _something;
  MyBlocStateInitialized(this._something);}

and the event like:

abstract class MyBlocEvent {}

class MyBlocEventInizialize extends MyBlocEvent{
  final string something;
  MyBlocEventInitialize(this.something);
}

Now, this is my test:

test('Should return MyBlocInitialized with a defined String', () {
    String _somethingString = 'Something';

expectLater(
_myBloc.state,emitsInOrder([
          MyBlocsStateUninitialized(),
          MyBlocStateInitialized(_somethingString)
        ]));

    _myBloc.dispatch(MyBlocEventInitialize(_somethingString);
}

The problem with this test is that it will just check if the bloc will yield MyBlocsStateUninitialized and MyBlocStateInitialized, but it will not check the string inside MyBlocStateInitialized. Actually I could also change in

expectLater(
_myBloc.state,emitsInOrder([
          MyBlocsStateUninitialized(),
          MyBlocInitialized('WRONG')
        ]));

    _myBloc.dispatch(MyBlocEventInitialize(_somethingString);
}

and it would still pass.

Upvotes: 0

Views: 962

Answers (1)

haroldolivieri
haroldolivieri

Reputation: 2283

Every time you have a comparable param on your state you have to pass it to the parent constructor - Equatable - as you did with MyBlocState, otherwise it will be initialized with an empty list and you will receive a false positive when compared.

From Equatable

The constructor takes an optional [List] of props (properties) which will be used to determine whether two [Equatables] are equal. If no properties are provided, props will be initialized to an empty [List].

abstract class MyBlocState extends Equatable {
  EnterCredentialsState([List props = const []]) : super(props)
}

class MyBlocStateInitialized extends MyBlocState {
  MyBlocStateInitialized(this._something): super([_something]);
  final String _something;
}

Upvotes: 2

Related Questions