Flutter: BLoC, testing streams

4,767

I've modified your code to use the RxDart's BehaviorSubject and it seems to work. You are using StreamController but I get error cause it doesn't have the value property.

final _controller1 = BehaviorSubject<String>();
final _controller2 = BehaviorSubject<bool>();

Sink get controller1Add => _controller1.sink;  
Stream<bool> get controller2Out => _controller2.stream;

  submit() {
    if (_controller1.value == null || _controller1.value.isEmpty) {
      print('Error');
      _controller2.sink.add(false);
      return;
    } else {
      print('OK');
      _controller2.sink.add(true);
    }
  }

The test:

bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));

bloc.controller1Add.add('test');
bloc.submit();
expect(bloc.controller2Out, emits(true));

bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));
Share:
4,767
Little Monkey
Author by

Little Monkey

Updated on December 07, 2022

Comments

  • Little Monkey
    Little Monkey over 1 year

    Testing the bloc pattern is not so clear to me. So, if I have these 2 stream controllers:

    final _controller1 = StreamController();
    final _controller2 = StreamController<bool>;
    
    Sink get controller1Add = _controller1.sink;
    Stream<bool> get controller2Out = _controller2.stream;
    

    and I want to test that, from this function:

    submit() {
    if (_controller1.value == null ||
            _controller1.value.isEmpty) {
              print(...)
          return;
        }else
           _controller2.sink.add(true);
        }
    

    the _controller2.stream should have true, how should I do?

    I tried something like:

      test("test", (){
        bloc.submit();
        expect(bloc.controller2Out, emitsAnyOf([true]));
      });
    

    but, of course, it didn´t work.

    • Günter Zöchbauer
      Günter Zöchbauer over 5 years
      What if you move bloc.submit(); below the expect(...) line? If submit() is sync()` there won't be any event emitted to subscribers that subscribe only afterwards.
    • Jordan Davies
      Jordan Davies over 5 years
      I think you have to make your test async and await the submit call.