2

I'm writing a Junit 4 test class comprising of 5 test methods. All these 5 test methods have same 10 assertEquals lines of code.

Would it be best practice to move these lines of codes in one method for e.g. public void callAssertions() { .... } and call this method from all tests?

Md. Sabbir Ahmed
  • 850
  • 8
  • 22
Caffeine Coder
  • 948
  • 14
  • 17
  • 2
    There are differing opinions on this - https://stackoverflow.com/questions/129693/is-duplicated-code-more-tolerable-in-unit-tests summarizes them quite well – matt freake Dec 12 '19 at 09:53

3 Answers3

1

I think that is a neater solution yes. Personally i always keep everything as separate as possible so every test is completely standalone. As long as that is the case it's okay.

Quadrivics
  • 181
  • 2
  • 10
1

As matt freake's comment mentions - Calling Junit Assertions via method call, there are differing opinions, but what I would do is separate assertions that are similar in nature.

So for example if you want to assert person's details, I would separate them into an assertPersonDetails() method - and so forth for other assertions. It really depends on the business logic underneath.

I wouldn't recommend separating them all into a generic named method like you suggested callAssertions()

Ultcyber
  • 396
  • 1
  • 6
1

As with all code, you should make sure that every test and every method in your test is readable and comprehensible.

You should have a clear pattern in your top test methods: given X, when Y, then Z. You can extract common code from each of the given/then/when parts, but you should not mix them.

So an assertThatZzzIsConsistent(...) method is OK, if it extracts only from the 'then' part. But an executeYyyAndAssertThatZzzIsConsistent(...) is not OK if it combines the 'when' and 'then' part.

GeertPt
  • 16,398
  • 2
  • 37
  • 61