1

I saw the answers here How to test abstract class in Java with jUnit? that says not to test the parent class for your subclasses, but test each of the concrete classes. However, the tests are the same for each subclass (beyond what subclass is being used/tested). What is the most efficient/elegant way to test all of these beyond copy pasting into new test classes and replacing the subclasses being tested? I could see doing a loop, but are there better options?

Community
  • 1
  • 1
Andrew
  • 6,295
  • 11
  • 56
  • 95
  • I completely disagree with the answer there. I've left a comment on it, so I will not repeat it here. You're welcome to take a look. – ethanfar Sep 17 '14 at 09:58

1 Answers1

1

Use Parameterized. Example, assuming that Foobar & Barbar both implement Baz interface

@RunWith(Parameterized.class)
public class BazTest {
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {     
                 { new Foobar(),
                   new Barbar(), }  
           });
    }

    private Baz baz;

    public BazTest(Baz baz) {
        this.baz= baz;
    }

    @Test
    public void test() {
        // assert something about baz
    }
}
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
  • Hmm, is there another way to instantiate them inside the tests? I ask because I construct Foo/bar with mockito mocks, and then in each test I change mock object output and construct foo/bar again to check behavior – Andrew Sep 15 '14 at 04:31
  • You can have whatever logic you want inside the data() method. – Matthew Farwell Sep 15 '14 at 05:45