Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Mocking a Stream

I am trying to test a class that uses WebSockets by mocking the socket

My class looks something like

class WebLoggerHandler{

   WebLoggerHandler(){

     var webSocket = new WebSocket('hostUrl');
     webSocket.onOpen.first.then((_) {
       webSocket.sendString('hello');
     });
   }
}

I am mocking the WebSocket class as follows

class MockWebSocket extends Mock implements WebSocket{        
  Stream<Event> onOpen;
}

The body of my test looks like

  var webSocket = new MockWebSocket();

  //fire the onOpen event 
  webSocket.onOpen = new Stream.fromFuture( new Future.value( new Event( "onOpen")));

  WebLoggerHandler underTest = new WebLoggerHandler();

  //test that the hello message was sent when the socket was opened
  webSocket.getLogs( callsTo("sendString", 'hello')).verify( happenedExactly(1))  

But it doesnt work as the onClose event happens after the checking of the webSocket logs has occurred.

How do I make the code wait for the Future to happen?

Thanks

like image 569
richard Avatar asked Dec 31 '25 06:12

richard


1 Answers

Read the API docs and have worked it out. The test needs to return a future

   test("it should send 'hello' to the server", () {

      return new Future.value().then((_) {

        webSocket.getLogs(callsTo("sendString", {'hello'})).verify(happenedExactly(1));

      });

   });
like image 52
richard Avatar answered Jan 06 '26 10:01

richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!