daily pastebin goal
77%
SHARE
TWEET

Untitled

a guest Aug 17th, 2018 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. How to display a name/label for each Parameterized Junit test in Eclipse [closed]
  2. public class PolySuite extends Suite {
  3.  
  4.   // //////////////////////////////
  5.   // Public helper interfaces
  6.  
  7.   /**
  8.    * Annotation for a method which returns a {@link Configuration}
  9.    * to be injected into the test class constructor
  10.    */
  11.   @Retention(RetentionPolicy.RUNTIME)
  12.   @Target(ElementType.METHOD)
  13.   public static @interface Config {
  14.   }
  15.  
  16.   public static interface Configuration {
  17.     int size();
  18.     Object getTestValue(int index);
  19.     String getTestName(int index);
  20.   }
  21.  
  22.   // //////////////////////////////
  23.   // Fields
  24.  
  25.   private final List<Runner> runners;
  26.  
  27.   // //////////////////////////////
  28.   // Constructor
  29.  
  30.   /**
  31.    * Only called reflectively. Do not use programmatically.
  32.    * @param c the test class
  33.    * @throws Throwable if something bad happens
  34.    */
  35.   public PolySuite(Class<?> c) throws Throwable {
  36.     super(c, Collections.<Runner>emptyList());
  37.     TestClass testClass = getTestClass();
  38.     Class<?> jTestClass = testClass.getJavaClass();
  39.     Configuration configuration = getConfiguration(testClass);
  40.     List<Runner> runners = new ArrayList<Runner>();
  41.     for (int i = 0, size = configuration.size(); i < size; i++) {
  42.       SingleRunner runner = new SingleRunner(jTestClass, configuration.getTestValue(i), configuration.getTestName(i));
  43.       runners.add(runner);
  44.     }
  45.     this.runners = runners;
  46.   }
  47.  
  48.   // //////////////////////////////
  49.   // Overrides
  50.  
  51.   @Override
  52.   protected List<Runner> getChildren() {
  53.     return runners;
  54.   }
  55.  
  56.   // //////////////////////////////
  57.   // Private
  58.  
  59.   private Configuration getConfiguration(TestClass testClass) throws Throwable {
  60.     return (Configuration) getConfigMethod(testClass).invokeExplosively(null);
  61.   }
  62.  
  63.   private FrameworkMethod getConfigMethod(TestClass testClass) {
  64.     List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Config.class);
  65.     if (methods.isEmpty()) {
  66.       throw new IllegalStateException("@" + Config.class.getSimpleName() + " method not found");
  67.     }
  68.     if (methods.size() > 1) {
  69.       throw new IllegalStateException("Too many @" + Config.class.getSimpleName() + " methods");
  70.     }
  71.     FrameworkMethod method = methods.get(0);
  72.     int modifiers = method.getMethod().getModifiers();
  73.     if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
  74.       throw new IllegalStateException("@" + Config.class.getSimpleName() + " method "" + method.getName() + "" must be public static");
  75.     }
  76.     return method;
  77.   }
  78.  
  79.   // //////////////////////////////
  80.   // Helper classes
  81.  
  82.   private static class SingleRunner extends BlockJUnit4ClassRunner {
  83.  
  84.     private final Object testVal;
  85.     private final String testName;
  86.  
  87.     SingleRunner(Class<?> testClass, Object testVal, String testName) throws InitializationError {
  88.       super(testClass);
  89.       this.testVal = testVal;
  90.       this.testName = testName;
  91.     }
  92.  
  93.     @Override
  94.     protected Object createTest() throws Exception {
  95.       return getTestClass().getOnlyConstructor().newInstance(testVal);
  96.     }
  97.  
  98.     @Override
  99.     protected String getName() {
  100.       return testName;
  101.     }
  102.  
  103.     @Override
  104.     protected String testName(FrameworkMethod method) {
  105.       return testName + ": " + method.getName();
  106.     }
  107.  
  108.     @Override
  109.     protected void validateConstructor(List<Throwable> errors) {
  110.       validateOnlyOneConstructor(errors);
  111.     }
  112.  
  113.     @Override
  114.     protected Statement classBlock(RunNotifier notifier) {
  115.       return childrenInvoker(notifier);
  116.     }
  117.   }
  118. }
  119.    
  120. @RunWith(PolySuite.class)
  121. public class PolySuiteExample {
  122.  
  123.   // //////////////////////////////
  124.   // Fixture
  125.  
  126.   @Config
  127.   public static Configuration getConfig() {
  128.     return new Configuration() {
  129.       @Override
  130.       public int size() {
  131.         return 10;
  132.       }
  133.  
  134.       @Override
  135.       public Integer getTestValue(int index) {
  136.         return index * 2;
  137.       }
  138.  
  139.       @Override
  140.       public String getTestName(int index) {
  141.         return "test" + index;
  142.       }
  143.     };
  144.   }
  145.  
  146.   // //////////////////////////////
  147.   // Fields
  148.  
  149.   private final int testVal;
  150.  
  151.   // //////////////////////////////
  152.   // Constructor
  153.  
  154.   public PolySuiteExample(int testVal) {
  155.     this.testVal = testVal;
  156.   }
  157.  
  158.   // //////////////////////////////
  159.   // Test
  160.  
  161.   @Ignore
  162.   @Test
  163.   public void odd() {
  164.     assertFalse(testVal % 2 == 0);
  165.   }
  166.  
  167.   @Test
  168.   public void even() {
  169.     assertTrue(testVal % 2 == 0);
  170.   }
  171.  
  172. }
  173.    
  174. import java.lang.annotation.ElementType;
  175. import java.lang.annotation.Retention;
  176. import java.lang.annotation.RetentionPolicy;
  177. import java.lang.annotation.Target;
  178. import java.lang.reflect.Constructor;
  179. import java.lang.reflect.InvocationTargetException;
  180. import java.lang.reflect.Method;
  181. import java.lang.reflect.Modifier;
  182. import java.util.ArrayList;
  183. import java.util.Arrays;
  184. import java.util.Collection;
  185. import java.util.List;
  186. import org.junit.Assert;
  187. import org.junit.internal.runners.ClassRoadie;
  188. import org.junit.internal.runners.CompositeRunner;
  189. import org.junit.internal.runners.InitializationError;
  190. import org.junit.internal.runners.JUnit4ClassRunner;
  191. import org.junit.internal.runners.MethodValidator;
  192. import org.junit.internal.runners.TestClass;
  193. import org.junit.runner.notification.RunNotifier;
  194.  
  195. public class LabelledParameterized extends CompositeRunner {
  196. static class TestClassRunnerForParameters extends JUnit4ClassRunner {
  197.     private final Object[] fParameters;
  198.  
  199.     private final String fParameterFirstValue;
  200.  
  201.     private final Constructor<?> fConstructor;
  202.  
  203.     TestClassRunnerForParameters(TestClass testClass, Object[] parameters, int i) throws InitializationError {
  204.         super(testClass.getJavaClass()); // todo
  205.         fParameters = parameters;
  206.         if (parameters != null) {
  207.             fParameterFirstValue = Arrays.asList(parameters).toString();
  208.         } else {
  209.             fParameterFirstValue = String.valueOf(i);
  210.         }
  211.         fConstructor = getOnlyConstructor();
  212.     }
  213.  
  214.     @Override
  215.     protected Object createTest() throws Exception {
  216.         return fConstructor.newInstance(fParameters);
  217.     }
  218.  
  219.     @Override
  220.     protected String getName() {
  221.         return String.format("%s", fParameterFirstValue);
  222.     }
  223.  
  224.     @Override
  225.     protected String testName(final Method method) {
  226.         return String.format("%s%s", method.getName(), fParameterFirstValue);
  227.     }
  228.  
  229.     private Constructor<?> getOnlyConstructor() {
  230.         Constructor<?>[] constructors = getTestClass().getJavaClass().getConstructors();
  231.         Assert.assertEquals(1, constructors.length);
  232.         return constructors[0];
  233.     }
  234.  
  235.     @Override
  236.     protected void validate() throws InitializationError {
  237.         // do nothing: validated before.
  238.     }
  239.  
  240.     @Override
  241.     public void run(RunNotifier notifier) {
  242.         runMethods(notifier);
  243.     }
  244. }
  245.  
  246. @Retention(RetentionPolicy.RUNTIME)
  247. @Target(ElementType.METHOD)
  248. public static @interface Parameters {
  249. }
  250.  
  251. private final TestClass fTestClass;
  252.  
  253. public LabelledParameterized(Class<?> klass) throws Exception {
  254.     super(klass.getName());
  255.     fTestClass = new TestClass(klass);
  256.  
  257.     MethodValidator methodValidator = new MethodValidator(fTestClass);
  258.     methodValidator.validateStaticMethods();
  259.     methodValidator.validateInstanceMethods();
  260.     methodValidator.assertValid();
  261.  
  262.     int i = 0;
  263.     for (final Object each : getParametersList()) {
  264.         if (each instanceof Object[])
  265.             add(new TestClassRunnerForParameters(fTestClass, (Object[]) each, i++));
  266.         else
  267.             throw new Exception(String.format("%s.%s() must return a Collection of arrays.", fTestClass.getName(), getParametersMethod().getName()));
  268.     }
  269. }
  270.  
  271. @Override
  272. public void run(final RunNotifier notifier) {
  273.     new ClassRoadie(notifier, fTestClass, getDescription(), new Runnable() {
  274.         public void run() {
  275.             runChildren(notifier);
  276.         }
  277.     }).runProtected();
  278. }
  279.  
  280. private Collection<?> getParametersList() throws IllegalAccessException, InvocationTargetException, Exception {
  281.     return (Collection<?>) getParametersMethod().invoke(null);
  282. }
  283.  
  284. private Method getParametersMethod() throws Exception {
  285.     List<Method> methods = fTestClass.getAnnotatedMethods(Parameters.class);
  286.     for (Method each : methods) {
  287.         int modifiers = each.getModifiers();
  288.         if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
  289.             return each;
  290.     }
  291.  
  292.     throw new Exception("No public static parameters method on class " + getName());
  293. }
  294.  
  295. public static Collection<Object[]> eachOne(Object... params) {
  296.     List<Object[]> results = new ArrayList<Object[]>();
  297.     for (Object param : params)
  298.         results.add(new Object[] { param });
  299.     return results;
  300. }
  301. }
  302.    
  303. @Parameters(name="namestring")
  304.    
  305. @RunWith(Parameterized.class)
  306. static public class FibonacciTest {
  307.     @Parameters(name= "{index}: fib({0})={1}")
  308.     public static Iterable<Object[]> data() {
  309.         return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
  310.                 { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
  311.     }
  312.  
  313.     private final int fInput;
  314.     private final int fExpected;
  315.  
  316.     public FibonacciTest(int input, int expected) {
  317.         fInput= input;
  318.         fExpected= expected;
  319.     }
  320.  
  321.     @Test
  322.     public void test() {
  323.         assertEquals(fExpected, fib(fInput));
  324.     }
  325.  
  326.     private int fib(int x) {
  327.         return 0;
  328.     }
  329. }
  330.    
  331. @Test
  332. public void name() {
  333.     Assert.assertEquals("", inboundFileName);
  334. }
  335.    
  336. private <T> void assertThat(final T actual, final Matcher<T> expected) {
  337.     Assert.assertThat(editThisToDisplaySomethingForYourDatum, actual, expected);
  338. }
  339.    
  340. public ExampleTest(final String testLabel, final int one, final int two) {
  341.     this.testLabel = testLabel;
  342.     // ...
  343. }
  344.  
  345. @Parameters
  346. public static Collection<Object[]> data() {
  347.     return asList(new Object[][]{
  348.         {"first test", 3, 4},
  349.         {"second test", 5, 6}
  350.     });
  351. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top