JUnit - Share Tests Of Different Implementations

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



JUnit - Share Tests Of Different Implementations



I'm looking for the most readable way to share tests of different implementations of an interface.



The most popular, but rather old question on this subject was -
Writing a single unit test for multiple implementations of an interface.



To the question above, 2 main and different answers were given -



I'm not satisfied with both answers.



Parameterized test - the answer doesn't include a code example of how to parameterize each subclass. Also, I personally have a hard time with parameterized test and I find the API not intuitive at all.



I always fear inheritance overusing, and I'm not sure if a test inheritance is a good practice.



I wonder what is the best answer to this question in 2018.




1 Answer
1



Probably not the most Java-like, but you can follow a table-driven test format. Using an local class, to keep test most readable, and keep context as close to real test as possible.



Note: this is very similar to underlying high-level approach of @RunWith(Parameterized.class)


@RunWith(Parameterized.class)


// Assuming Animal interface has a `public boolean canDance()`

@Test
public void TestAnimalCanDance()
class Tester
String errMsgFmt = "%s failed the test";
boolean expected;
Animal animal;
public Tester(boolean expected, Animal animal)
this.expected = expected;
this.animal = animal;



Tester dog = new Tester(true, new Dog());
Tester cat = new Tester(false, new Cat());
Tester monkey = new Tester(false, new Monkey());
Tester tests = Arrays.asList(dog, cat, monkey);

for (Tester t: tests)
boolean actual = t.canDance();
assertTrue(actual == t.expected);







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard