Pages

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 System.in. 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.in & 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, System.in).doMain();  
   }  

To test use ByteArray Streams:
     final List<String> firstClientLines = new ArrayList<>();  
     try (  
         PrintStream firstOut = new PrintStream(new ByteArrayOutputStream()) {  
           @Override  
           public void println(String str) {  
             firstClientLines.add(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