Friday, July 3, 2015

Testing your main method

I wrote a lot of simple applications, mostly to just try things out, that run on text console and for user interactions use System.out.println and An issue is how to test these programs. Here is a simple way. Move your logic from your static main method to the object and parameterize the & System.out. Like from this :
 public class ShouterMain {  
   public static void main(String... args) throws Exception {  
     String id = UUID.randomUUID().toString();  
     final MulticastSocket socket = new MulticastSocket(4444);  

to this:
   public static void main(String... args) throws Exception {  
     new ShouterMain(System.out,;  

To test use ByteArray Streams:
     final List<String> firstClientLines = new ArrayList<>();  
     try (  
         PrintStream firstOut = new PrintStream(new ByteArrayOutputStream()) {  
           public void println(String str) {  
         InputStream firstIn = new ByteArrayInputStream(new byte[]{});  
     ) {  
       new ShouterMain(firstOut, firstIn).doMain();  
       Assert.assertEquals("Someone shouted: 'I am Second!'", firstClientLines.get(0));  

No comments:

Post a Comment