简体   繁体   中英

Calling Junit Assertions via method call

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 eg public void callAssertions() { .... } and call this method from all tests?

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()

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM