Testing SwiftNIO

Hi everyone,

I'm experimenting with the new async features of SwiftNIO. While experimenting I notice I would like to take a more test driven approach.

For this NIO server, input and output are just byte buffers containing text.

How can I write tests that verify behavior such as:

  • Given a NIO server, when a new connection comes in, receive a 'welcome' message;
  • Given a connection to the server, when I send the message 'Foo', receive 'bar' as response.
  • Given a connection to the server, when the client request the connection to be closed, receive a 'bye' message.

I assume I'll need some boilerplate to setup the server and a client of some form. Anyone have an example?

Kind regards,

Maarten Engels

1 Like

So it depends what you want to test exactly. If you want to do a full integration test you can spin up your ServerBootstrap and use a ClientBootstrap to drive it. However, this would involve testing the whole NIO stack + whatever ChannelHandlers your put in. If you just want to test your business logic the new NIOAsyncChannel is providing some testing facilities which allow you to drive the NIOAsyncChannelInboundStream and the NIOAsyncChannelOutboundWriter. With this you should be able to unit test your business logic that resides outside of the channel pipeline.

Hi Franz,

I think in this case I would like to do a full integration test, as I want to make sure the server as a whole behaves as expected. And it would also allow me to perform tests for edge cases like interrupted connections, incomplete data, large data volumes coming in, etc.

The business logic itself, I will mostly test outside of NIO.

Do you have an example of such a ServerBootstrap and ClientBootstrap?

KR Maarten

This is a test that uses the new async bootstraps to spin up a ServerBootstrap and a ClientBootstrap. Let me know if this is a good starting point for you or if you have more questions!

This looks like an excellent example. :pray:

I got it running based on you example! It has a lot of boilerplate code, but at least tests:

  • Seem to be stable
  • Timeout (when waiting to long for the next value in the iterator)
1 Like