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();
}
}
source
share