1   package org.kohsuke.args4j;
2   
3   import java.io.IOException;
4   import java.io.OutputStream;
5   
6   import junit.framework.TestCase;
7   
8   
9   /***
10   * Base class for Args4J Tests.
11   * It instanstiates the test object, the CmdLineParser for
12   * that test object and provides a String array for passing 
13   * to the parser.
14   * 
15   * @author Jan Matèrne
16   */
17  public abstract class Args4JTestBase<T> extends TestCase {
18  
19      CmdLineParser parser;
20      String[] args;
21      T testObject;
22  
23      /***
24       * Specifies which concrete object to return as test object.
25       * @return the test object
26       */
27      public abstract T getTestObject();
28  
29      /***
30       * Initializes the testObject and the parser for that object. 
31       * @see junit.framework.TestCase#setUp()
32       */
33      @Override
34      protected void setUp() throws Exception {
35          super.setUp();
36          testObject = getTestObject();
37          parser = new CmdLineParser(testObject);
38      }
39      
40      /***
41       * Checks the number of lines of the parsers usage message.
42       * @param expectedLength 
43       * @see TestCase#assertEquals(String, int, int)
44       * @see Args4JTestBase#getUsageMessage()
45       */
46      public void assertUsageLength(int expectedLength) {
47          assertEquals("Wrong amount of lines in usage message", getUsageMessage().length, expectedLength);
48      }
49      
50      /***
51       * Extracts the usage message from the parser as String array.
52       * @return the usage message
53       * @see CmdLineParser#printUsage(OutputStream)
54       */
55      public String[] getUsageMessage() {
56          Stream2String s2w = new Stream2String();
57          parser.printUsage(s2w);
58          return s2w.getString().split(System.getProperty("line.separator"));
59      }
60      
61      /***
62       * Utility class for capturing an OutputStream into a String.
63       * @author Jan
64       */
65      private class Stream2String extends OutputStream {
66          private StringBuffer sb = new StringBuffer();
67          
68          @Override
69          public void write(int b) throws IOException {
70              sb.append((char)b);
71          }
72  
73          public String getString() {
74              return sb.toString();
75          }
76      }
77  
78  }