1 package com.beust.jcommander; 2 3 import org.testng.Assert; 4 import org.testng.annotations.Test; 5 6 import java.util.List; 7 8 /** 9 * Tests for @Parameter on top of methods. 10 */ 11 @Test 12 public class MethodSetterTest { arityStringsSetter()13 public void arityStringsSetter() { 14 class ArgsArityStringSetter { 15 16 @Parameter(names = "-pairs", arity = 2, description = "Pairs") 17 public void setPairs(List<String> pairs) { 18 this.pairs = pairs; 19 } 20 public List<String> getPairs() { 21 return this.pairs; 22 } 23 public List<String> pairs; 24 25 @Parameter(description = "Rest") 26 public void setRest(List<String> rest) { 27 this.rest = rest; 28 } 29 public List<String> rest; 30 } 31 ArgsArityStringSetter args = new ArgsArityStringSetter(); 32 String[] argv = { "-pairs", "pair0", "pair1", "rest" }; 33 new JCommander(args, argv); 34 35 Assert.assertEquals(args.pairs.size(), 2); 36 Assert.assertEquals(args.pairs.get(0), "pair0"); 37 Assert.assertEquals(args.pairs.get(1), "pair1"); 38 Assert.assertEquals(args.rest.size(), 1); 39 Assert.assertEquals(args.rest.get(0), "rest"); 40 } 41 setterThatThrows()42 public void setterThatThrows() { 43 class Arg { 44 @Parameter(names = "--host") 45 public void setHost(String host) { 46 throw new ParameterException("Illegal host"); 47 } 48 } 49 boolean passed = false; 50 try { 51 new JCommander(new Arg(), "--host", "host"); 52 } catch(ParameterException ex) { 53 Assert.assertEquals(ex.getCause(), null); 54 passed = true; 55 } 56 Assert.assertTrue(passed, "Should have thrown an exception"); 57 } 58 getterReturningNonString()59 public void getterReturningNonString() { 60 class Arg { 61 private Integer port; 62 63 @Parameter(names = "--port") 64 public void setPort(String port) { 65 this.port = Integer.parseInt(port); 66 } 67 68 public Integer getPort() { 69 return port; 70 } 71 } 72 Arg arg = new Arg(); 73 new JCommander(arg, "--port", "42"); 74 75 Assert.assertEquals(arg.port, new Integer(42)); 76 } 77 noGetterButWithField()78 public void noGetterButWithField() { 79 class Arg { 80 private Integer port = 43; 81 82 @Parameter(names = "--port") 83 public void setPort(String port) { 84 this.port = Integer.parseInt(port); 85 } 86 } 87 Arg arg = new Arg(); 88 JCommander jc = new JCommander(arg, "--port", "42"); 89 ParameterDescription pd = jc.getParameters().get(0); 90 Assert.assertEquals(pd.getDefault(), 43); 91 } 92 93 @Test(enabled = false) main(String[] args)94 public static void main(String[] args) throws Exception { 95 new MethodSetterTest().noGetterButWithField(); 96 } 97 } 98