Recently I was working on a Java project where I had to connect to a server using the Java 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 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 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 server would've required in-depth knowledge about the protocol, I settled for creating a mock for the client itself.

Say we have a Java class that uses the 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 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.