Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit: Use same test object in multiple test classes

Tags:

java

junit

I have multiple, individual test classes which all use the same test object. At the moment I'm using @Before in each of these classes, which is obviously not a very good solution.

One option of course is to inherit from an abstract class which creates this object. As stated here, this is not a good idea as well.

Another option would be External Resource, but that is - as the name says - for resources rather than test objects.

I feel like I'm missing something since this must be a basic task in JUnit.

like image 210
David Avatar asked Apr 25 '17 21:04

David


2 Answers

You might be looking for a TestRule. To quote the Javadoc:

A TestRule is an alteration in how a test method, or set of test methods, is run and reported. A TestRule may add additional checks that cause a test that would otherwise fail to pass, or it may perform necessary setup or cleanup for tests, or it may observe test execution to report it elsewhere. TestRules can do everything that could be done previously with methods annotated with Before, After, BeforeClass, or AfterClass, but they are more powerful, and more easily shared between projects and classes.

It then goes on to list a few types, of which ExternalResource is one; but there are others also.

Given that you talk about doing things better than using @Before methods, and you're wanting to share between classes, this sounds very much like what you are describing.

like image 140
Andy Turner Avatar answered Oct 21 '22 14:10

Andy Turner


Congratulations you've discovered something to improve in your design! This is an excellent result from writing tests.

You say you are using the same test object in multiple tests. I assume your tests are testing different classes. I expect you have uncovered some common behaviour in those different classes that could abstract out into a new class.

Afterwards your test object would test the new class, you could remove it from th other tests, and whatever behaviour remains is different each time. Seems like a good outcome!

like image 45
KarlM Avatar answered Oct 21 '22 13:10

KarlM