Recently I was working on a Java project where I had to connect to a socket.io server using the Java socket.io client. When that was done, I had to write tests for it, but I couldn't find any mocking library that would help you mock a socket.io server/client. Ideally, I was thinking of something similar to mockserver client, but as I didn't find that, I looked for at least a resource online that demonstrates how to mock a socket.io client in Java, but no luck. The closest thing I found was this github issue which was helpful, but I thought it'd be really helpful if I put together that article that I never found.

So yeah, since implementing a mock socket.io server would've required in-depth knowledge about the socket.io protocol, I settled for creating a mock for the socket.io client itself.

Say we have a Java class that uses the socket.io client like so:

This class primarily has 2 methods:
1. getSocket - which returns the socket
2. useTheSocket - which uses the socket

Next, we'd have a mock socket.io client class like so:

The goals of the mock socket are to:
1. Keep the entire Socket interaction in a single Thread
2. Register all the events emitted by the client

And in your test you can do something this:



And that's that about that! I hope you find this approach useful for use-case. Also if you found this article useful in anyway, please feel free to reshare.