jd96
jd96

Reputation: 615

How can I add a spring bean to a Spring Boot test class?

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

Answers (2)

Michiel
Michiel

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

efire-net
efire-net

Reputation: 52

Have you tried annotating TestHelper with @Component?

Upvotes: 0

Related Questions