Help in real TDD using Java

Now I am looking for help to use TDD for an example in the real world. Most shows are too simple and don't really show how to test and regroup more complex classes. Here is an example of code that uses both a stream and a network socket. Can anyone explain how to create an isolated Unit Test for such a class? Thank.

public class BaseHandler  extends Thread {
  protected Socket mClientSocket;
  protected BufferedReader is = null;
  protected BufferedWriter os = null;
  private Logger mLogger = Logger.getLogger(WebTestController.class.getName());
  protected WebTestController mWebTestController;

  /*********************************************************************
   * 
   * @param piPort - int port to listen on
   */
  public BaseHandler(){
  }


  /*********************************************************************** cleanup
   * Ensure sockets are closed as to not run into bind errors
   */
  protected void cleanup() {
    try {
      if (is != null)
        is.close();
      if (os != null)
        os.close();
      if (mClientSocket != null)
        mClientSocket.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    mLogger.info("cleaning up a socket");
  }

  /***********************************************************************************
   * Sends a message to the current socket
   * @param pMessage
   */
  protected void writeToSocket(String pMessage){
      try {
          os = new BufferedWriter(
            new OutputStreamWriter(mClientSocket.getOutputStream()));

        }
        catch (IOException e) {
          e.printStackTrace();
          cleanup();
          return;
        }
        try {
            os.write(pMessage, 0, pMessage.length());
            os.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        cleanup();
  }

}
+5
source share
5 answers

Here are some practical things you need to do to reduce your testing problems:

  • You do not have a class that inherits Thread. Do this instead of Runnable, because you can test Runnable in isolation.
  • , Logger WebTestController (. "mocking" ).
  • - , . , . , , , , .

TDD . - - . , . TDD , - , .

+5

.

, IO, concurrency - . , IO, , , mock socket.

concurrency - . , .

+5

AFAIK Test Drive Development. , , .

, Socket ServerSocket .

+1

"" , , java.lang.Thread. run(), , java.lang.Thread.

cleanup() writeToSocket, run().

BaseHandler, , .

, , . , TDD.

+1

SRP (Single Responsibility Priciple). . . Spring IoC.

If you shared the class, you would have noticed that it would be much easier to test. You can supply mock-ups for these components and enter them as you wish in each test case, as this suits you best.

+1
source

All Articles