0

Sometimes it makes sense to have more than one assertion in a unit test method, e.g.

@Test
public void testMapReduceProcessing() {
    Tuple tuple = new MetadataTuple();
    Processor instance = new Processor();
    instance.process(tuple);
    assertEquals(State.PROCESSED, tuple.getState());
    assertEquals(1, tuple.getProcessCount());
}

PMD and possibly other static analysis tools which I might introduce in the future and want to consider during programming now would raise a JUnitTestContainsTooManyAsserts warning because more than one assert[...] is present. I could:

  • split the methods, but that seems overkill and the recommendation to have only one assert per unit test method doesn't apply here because there's no advantage in splitting here.
  • assertTrue(a.equals(b) && c.equals(d)) which would complicate the assert failure message and also be bad style because equals should use assertEquals.
  • accept that there's no other solution and suppress the PMD check.

I'm not happy with all of them. Is there any elegant approach? I'm looking for JUnit 5 approaches and don't mind extra dependencies.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
  • From what you're describing, you _want_ to put two asserts in one method and you're trying to find a way to avoid the warning. If you don't agree with the warning, suppress it or turn it off. If you _do_ agree with it, maybe you should split the methods rather than trying to find a dodge around it. – khelwood Jun 26 '18 at 13:13
  • Such warnings are just wrong. It's perfectly normal, correct, and even desirable to have multiple assertions in a test. One test should test *one thing*, of course, but that doesn't mean *one assertion*. – Rogério Jun 26 '18 at 18:27

0 Answers0