Junior — Middle
How can you ensure a unified context setup for tests located in different classes?
sobes.tech AI
Answer from AI
To ensure a unified test context setup across different classes in Java, a common base class or configuration class is usually used, which initializes the necessary context.
For example, in Spring tests, you can create a class with the @ContextConfiguration annotation and use it as a base for all test classes. You can also use the @BeforeClass annotation in the base class to perform initialization once before all tests run.
Example:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public abstract class BaseTest {
@BeforeClass
public static void setUpContext() {
// Initialization of the common context
}
}
public class FirstTest extends BaseTest {
@Test
public void testSomething() {
// test
}
}
public class SecondTest extends BaseTest {
@Test
public void testAnother() {
// test
}
}
Thus, the context is initialized once in the base class and is accessible in all subclasses.