As a developer, we have to ensure that our codes are high-quality, fully tested and peer-reviewed before delivering. Today the topic is how to mock java socket server to test Socket related application.

Mock  Overview:

Mock technology is primarily used to mock applications which are not easily to build in the structure (such as HttpServletRequest object must from ServletContext) or some complex objects (such as JDBC’s ResultSet object) , It is configured to simulate the object that it replaces in a simple way.

Currently, the Java Mock Test tools in marking are EasyMock, JMock, MockCreator, Mockrunner, MockMaker, etc.

Environment: Easymock, Jdk1.5, Junit, IDEA.

EasyMock provides Mock Objects for interfaces (and objects through the class extension) by generating them on the fly using Java’s proxy mechanism. EasyMock is a perfect one for Test-Driven Development.

//this method simply send the socket request and read 
//the response from server.
public String sendRequest(String command) throws Exception {
    Socket socket = new Socket("localhost", 6539);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    ...
    return response
 }

Create a simple Socket server to listen on the request sent by client.

public class TMSocketServer {
class SocketThread extends Thread {
   public void run() {
      while (serverSocket != null && !stop) {
      Socket socket = null;
      try {
        socket = serverSocket.accept();
        //there you can get the socket client request,
        call the interface ServerRequestHandle.handleRequest() method
        get return to get back to socket client.
     }
}

public interface ServerRequestHandle {
    Object handleRequest(Object request);
}

Here is a test case of method sendRequest

public void testSendRequest () {
    ServerRequestHandle handle = EasyMock.createMock
(ServerRequestHandle.class);
    TMSocketServer server = new TMSocketServer (handle );
    server .start()
    expect(handle.handleRequest(eq(...))
    ).andReturn(
       ...
    );
    replay(handle);
    sendRequest();
    verify(handle);
}