1

I love the way that you can write clean concise code in Dart, but it appears that Dart is one of those languages that it easy to write but hard to test!

For example, given the following fairly simple method, how does one go about unit testing it?

typedef void HandleWebSocket(WebSocket webSocket);

Router createWebSocketRouter(HttpServer server, String context, HandleWebSocket handler) {

  var router = new Router(server);

  router.serve(context).transform(new WebSocketTransformer()).listen(handler);

  return router;
}

You need to somehow replace the new Router() with some sort of factory method that returns a mock. The mock then needs to return a mock when serve is called. That then needs to have a mock transform* method that returns a mock stream.....and at that point most people will give up!

I have managed to write a unit test using the above approach but as it required 80 odd lines and polluted the actual class with a factory method I can hardly say I am happy with it!

Is there a better way of doing this?

richard
  • 2,887
  • 5
  • 26
  • 36
  • There is a similar question http://stackoverflow.com/questions/24224525 Maybe there is also a mock class for WebSocket available. – Günter Zöchbauer Jun 16 '14 at 10:12
  • I am using the testing of this procedure as a example of how hard I have found Dart Unit testing to be. Is it a sign that there is something missing from the Dart language or API? – richard Jun 16 '14 at 10:40
  • I wouldn't expect testing methods which use WebSocket (or other connection to external systems) to be easy, especially when there are not ready-to-use mock objects available. If there is not yet a mock object available this this that what might be missing. Otherwise testing with dart is fine (IMHO) but there is always something that can be improved ... – Günter Zöchbauer Jun 16 '14 at 10:43
  • What exactly do you want to test in this method anyway? – Günter Zöchbauer Jun 16 '14 at 10:45
  • Basic principle of TTD: never write a line of production code until you have a failing test. :) But you are right, testing a API is hard – richard Jun 16 '14 at 23:30
  • You are right, but you should think about what you actually try to test anyway. If you only test API functionality this might not be worth the time. – Günter Zöchbauer Jun 17 '14 at 04:08
  • At some point I will have to try write an test that will start up a server and then open a websocket to it. As I want to write a Dart unit test to do this I no doubt will be bugging you again :) – richard Jun 17 '14 at 05:26

0 Answers0