Guest User

Untitled

a guest
Jan 24th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. package test;
  2.  
  3. import java.util.List;
  4.  
  5. import org.testng.Assert;
  6. import org.testng.annotations.BeforeTest;
  7. import org.testng.annotations.Test;
  8.  
  9. import com.beust.jcommander.IStringConverter;
  10. import com.beust.jcommander.IStringConverterFactory;
  11. import com.beust.jcommander.JCommander;
  12. import com.beust.jcommander.Parameter;
  13.  
  14. public class JCommanderTest {
  15.  
  16. public static class Args {
  17. //this works
  18. @Parameter(names = "-single")
  19. HostPort single;
  20.  
  21. //this works because i define converter explicitly
  22. @Parameter(names = "-explicit", converter = HostPortConverter.class)
  23. List<HostPort> explicitConverter;
  24.  
  25. //i would expect this to work but...
  26. @Parameter(names = "-implicit")
  27. List<HostPort> implicitConverter;
  28. }
  29.  
  30. public static class HostPort {
  31. public String host;
  32. public Integer port;
  33. }
  34.  
  35. public static class HostPortConverter implements IStringConverter<HostPort> {
  36. public HostPort convert(String value) {
  37. HostPort result = new HostPort();
  38. String[] s = value.split(":");
  39. result.host = s[0];
  40. result.port = Integer.parseInt(s[1]);
  41.  
  42. return result;
  43. }
  44. }
  45.  
  46. public static class Factory implements IStringConverterFactory {
  47. public Class<? extends IStringConverter<?>> getConverter(Class forType) {
  48. if (forType.equals(HostPort.class)) return HostPortConverter.class;
  49. else return null;
  50. }
  51. }
  52.  
  53. public Args args;
  54. public JCommander jc;
  55.  
  56. @BeforeTest
  57. public void setUp() {
  58. args = new Args();
  59. jc = new JCommander(args);
  60. jc.addConverterFactory(new Factory());
  61. }
  62.  
  63. @Test
  64. public void testSingle() {
  65. jc.parse("-single", "localhost:80");
  66. Assert.assertEquals(args.single.host, "localhost");
  67. Assert.assertEquals(args.single.port.intValue(), 80);
  68. Assert.assertEquals(args.single.getClass(), HostPort.class);
  69. }
  70.  
  71. @Test
  72. public void testExplicit() {
  73. jc.parse("-explicit", "localhost:80", "-explicit", "foo:80");
  74. // :s how to check it is a List<HostPort> ??
  75. Assert.assertTrue(args.explicitConverter instanceof List<?>);
  76. for (HostPort h : args.explicitConverter) {
  77. Assert.assertTrue(h instanceof HostPort);
  78. }
  79. }
  80.  
  81. @Test
  82. public void testImplicit() {
  83. jc.parse("-implicit", "localhost:80", "-explicit", "foo:80");
  84. Assert.assertTrue(args.implicitConverter instanceof List<?>);
  85. //this fails!
  86. for (HostPort h : args.implicitConverter) {
  87. Assert.assertTrue(h instanceof HostPort);
  88. }
  89. }
  90.  
  91. }
Add Comment
Please, Sign In to add comment