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.
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. ATestRule
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 withBefore
,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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With