Reputation: 217
I am aware there is another question in this forum which MAY seem similar. Please read through before marking as duplicate.
I am searching for a way to run a test, which is defined in another class, in a way that it'll go through the @before annotation.
public TestClass1 {
@before
public void setup() throws Exception{
super.setup();
}
@Test
public void testSomething(){...}
}
public TestClass2 {
@Test
public void testSomethingAndSomethingElse() {
// Somehow execute testSomething() in a way which will force
it to go through the @before
// and then test something else
}
}
In the similar online question there're 2 suggestions:
1. Extends TestClass2 from TestClass1 - which is impossible for me since I extend another class already.
2. To access TestClass1 from TestClass2 using delegation, like this:
// Instantiate TestClass1 as a member of TestClass2
public TestClass2 {
private TestClass1 one = new TestClass1();
public void testSomethingAndSomethingElse1() {
one.testSomething();
}
}
The problem here is that when calling one.testSomething() - you will not go through the @before annotation of TestClass1, which in my case is needed in order to init other objects.
Is there another way perhaps?
The usage is for integration tests and not unit tests. I need the ability to use @test inside another @test, and not any other workaround.
Upvotes: 3
Views: 1966
Reputation: 18792
Assuming TestClass1
and TestClass2
subclass of the same class consider pulling up the @before
annotation to their super class:
public class TestCalss {
@Before
public void setUp() throws Exception {
System.out.println("setup");
}
}
public class TestCalss1 extends TestCalss{}
public class TestCalss2 extends TestCalss{}
Upvotes: 0
Reputation: 20258
If you try to reuse the same code in many test classes I suggest using @Rule
from JUnit
framework. Maybe ExternalResource
is what you need:
public class SetupResource extends ExternalResource {
@Override
protected void before() throws Throwable {
//setup the code
}
}
Put the code you want in before()
method and then define JUnit
Rule
like that:
@Rule
public ExternalResource resource = new SetupResource ()
Upvotes: 1