我现在正在寻求帮助,将TDD用作真实世界的例子.大多数节目过于简单,并没有真正展示如何测试和重新考虑更复杂的类.以下是使用线程和网络套接字的代码示例.有人可以解释如何为这样的类创建一个独立的单元测试吗?谢谢.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
不要创建这样的类.
将逻辑分解为与IO相关的部分和与并发相关的部分会更好.然后可以测试与IO相关的部分,例如,使用模拟套接字实现.
但是,测试与并发相关的逻辑会更复杂.这取决于您想要实现的行为.
| 归档时间: |
|
| 查看次数: |
584 次 |
| 最近记录: |