Reputation: 615
I have an integration test which makes use of a test helper class. Currently I create this test helper class with the junit BeforeEach
method:
@AutoConfigureMockMvc
@SpringBootTest
public class EmployeeControllerIT {
@Autowired
private MockMvc mockMvc;
private TestHelper testHelper;
@BeforeEach
public void setup() {
this.testHelper = new TestHelper();
}
...
}
However, given I am using Spring, I'd like to use dependency injection. How can I add TestHelper
to the application context so I can autowire it as follows:
@AutoConfigureMockMvc
@SpringBootTest
public class EmployeeControllerIT {
@Autowired
private MockMvc mockMvc;
@Autowired
private TestHelper testHelper;
....
}
Upvotes: 2
Views: 2785
Reputation: 3500
Instead of initializing the TestHelper
in the @BeforeEach
method, add a static inner class annotated with @TestConfiguration
and declare the TestHelper
as a bean:
@AutoConfigureMockMvc
@SpringBootTest
public class EmployeeControllerIT {
@Autowired
private MockMvc mockMvc;
@Autowired
private TestHelper testHelper;
@TestConfiguration
public static class TestConfig {
@Bean
public TestHelper testHelper(SomeClass someClass) {
return new TestHelper(someClass);
}
}
...
}
Upvotes: 3