Closed
Description
Bug description
When using @SpringBatchTest
on a test class enclosing a @Nested
class, two separate Spring test contexts are created, one to execute the test methods in the outer class and another for the ones in the inner class.
Environment
Spring Batch 5.2.1 (originally detected on Spring Batch 4.3.10)
Steps to reproduce
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.junit.jupiter.api.Assertions.assertSame;
@SpringJUnitConfig
@SpringBatchTest
class WithAnnotationTest {
@Autowired
ApplicationContext context;
@Nested
class Inner {
@Autowired
ApplicationContext context;
@Test
void test() {
assertSame(WithAnnotationTest.this.context, context); // should succeed but fails
}
}
}
Expected behavior
A single test context should be available for both the outer and the inner class, like in the following example:
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.junit.jupiter.api.Assertions.assertSame;
@SpringJUnitConfig
class WithoutAnnotationTest {
@Autowired
ApplicationContext context;
@Nested
class Inner {
@Autowired
ApplicationContext context;
@Test
void test() {
assertSame(WithoutAnnotationTest.this.context, context); // succeeds
}
}
}
Workaround
Applying @SpringBatchTest
also on the inner class prevents the creation of the additional test context:
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.junit.jupiter.api.Assertions.assertSame;
@SpringJUnitConfig
@SpringBatchTest
class WithDoubleAnnotationTest {
@Autowired
ApplicationContext context;
@Nested
@SpringBatchTest
class Inner {
@Autowired
ApplicationContext context;
@Test
void test() {
assertSame(WithDoubleAnnotationTest.this.context, context); // succeeds
}
}
}
Minimal Complete Reproducible example
https://github.com/scordio/spring-boot-playground/tree/spring-batch-4738-reproducer