1 10 11 package org.apache.commons.cli; 12 13 import junit.framework.Test; 14 import junit.framework.TestCase; 15 import junit.framework.TestSuite; 16 17 21 public class ParseRequiredTest extends TestCase 22 { 23 24 private Options _options = null; 25 private CommandLineParser parser = new PosixParser(); 26 27 public static Test suite() { 28 return new TestSuite(ParseRequiredTest.class); 29 } 30 31 public ParseRequiredTest(String name) 32 { 33 super(name); 34 } 35 36 public void setUp() 37 { 38 _options = new Options() 39 .addOption("a", 40 "enable-a", 41 false, 42 "turn [a] on or off") 43 .addOption( OptionBuilder.withLongOpt( "bfile" ) 44 .hasArg() 45 .isRequired() 46 .withDescription( "set the value of [b]" ) 47 .create( 'b' ) ); 48 } 49 50 public void tearDown() 51 { 52 53 } 54 55 public void testWithRequiredOption() 56 { 57 String [] args = new String [] { "-b", "file" }; 58 59 try 60 { 61 CommandLine cl = parser.parse(_options,args); 62 63 assertTrue( "Confirm -a is NOT set", !cl.hasOption("a") ); 64 assertTrue( "Confirm -b is set", cl.hasOption("b") ); 65 assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); 66 assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); 67 } 68 catch (ParseException e) 69 { 70 fail( e.toString() ); 71 } 72 } 73 74 public void testOptionAndRequiredOption() 75 { 76 String [] args = new String [] { "-a", "-b", "file" }; 77 78 try 79 { 80 CommandLine cl = parser.parse(_options,args); 81 82 assertTrue( "Confirm -a is set", cl.hasOption("a") ); 83 assertTrue( "Confirm -b is set", cl.hasOption("b") ); 84 assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); 85 assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); 86 } 87 catch (ParseException e) 88 { 89 fail( e.toString() ); 90 } 91 } 92 93 public void testMissingRequiredOption() 94 { 95 String [] args = new String [] { "-a" }; 96 97 try 98 { 99 CommandLine cl = parser.parse(_options,args); 100 fail( "exception should have been thrown" ); 101 } 102 catch (ParseException e) 103 { 104 if( !( e instanceof MissingOptionException ) ) 105 { 106 fail( "expected to catch MissingOptionException" ); 107 } 108 } 109 } 110 111 } 112 | Popular Tags |