Should I split reuse methods in JUnit?

I have the following JUnit test. The method I'm testing is pretty simple, it just gets a number and returns a list with its divisors. I don’t want to repeat the test code many times, so I created a helper method, testDivisorsAux :

 @Test public final void testDivisors() { testDivisorsAux(1, new int[] { 1 }); testDivisorsAux(6, new int[] { 1, 2, 3, 6 }); testDivisorsAux(0, new int[] { }); ... } private final void testDivisorsAux(final int number, final int[] expected) { List<Integer> divisors = Util.divisors(number); assertSame(divisors.size(), expected.length); for (int i : expected) { assertTrue(divisors.contains(i)); } } 

Everything works fine, I'm just wondering ... Is this a bad practice? Should I write the test differently? Perhaps save all the code in the @Test method?

PMD tells me that JUnit tests should include assert () or fail () (for the first method), and JUnit 4 tests that run tests should use the @Test annotation (for the second). I know that PMD only uses regex (well, it's actually XPath) to determine which rules I'm breaking ... so I tend to think that this is just a β€œfalse positive” warning. But in any case, I would like to know that I am doing something wrong. (Appart from writing tests is 4 times longer than the test method :)

While I was looking for questions like this, I found something called parameterized tests ... but it looks like it is something focused on much larger scenarios, right?

+6
junit pmd
source share
2 answers

Personally, I believe that good practice for this. There is little risk of going too far and creating a ton of code to run your test, in which case you should rethink the design of the material you're testing. You really don't want to write tests to test your tests, but the example you give seems to be great, and that means your test cases are much simpler.

I did not use PMD, and personally, I would try to configure it to enable these warnings. If they bother you, you can change your code to get rid of them. I assume that the second warning was caused by the fact that your helper method starts with a word test. In junit3, all methods that start with a test are tests. Why not rename the testDivisorsAux method as assertDivisors - perhaps the method that starts with assert will also help with the 1st warning.

+5
source share

As Adam Butler said, a method starting with assert will resolve this warning.

So, in your case, rename testDivisorsAux to assertDivisorsAux, fixing it.

See also http://pmd.sourceforge.net/pmd-4.3.0/xref/net/sourceforge/pmd/rules/junit/JUnitTestsShouldContainAsserts.html for code that validates the rule.

0
source share

All Articles