Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > Unit Testing Sockets

Unit Testing Sockets

It is a kind of different when we write unit tests for sockets because you have to instantiate them in a thread and then get a handle of the class to test different methods.

In the last post we had talked about the ServerSocketChannel example. In this post we will see how to unit test this class

public class ServerSocketChannelUnitTest {

private static int TEST_PORT = 9991;

private static BlockingServerSocketChannel ssc;

/**
* This will set up the server socket class in a new thread.
* This is required else , the test will hand once you instantiate server socket channel
*
*/
@BeforeClass
public static void before() {
System.out.println(“@Before”);

Thread myThread = new Thread() {
public void run() {

System.out.println(“@Before myThread run()”);

try {

ssc = new BlockingServerSocketChannel();
ssc.setup(TEST_PORT);

System.out.println(“Finished Instantiating “);

} catch (Exception e) {
e.printStackTrace();
}
}
};

try {
// required so that there is enough time before the next methods are invoked
System.out.println(“Sleep Started”);
myThread.start();
Thread.sleep(10000);
System.out.println(“Sleep finished”);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
  1. No comments yet.
  1. No trackbacks yet.
Get Adobe Flash playerPlugin by wpburn.com wordpress themes