简体   繁体   中英

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;

    ....
}

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);
        }
    }

    ...
}

您是否尝试过使用 @Component 注释 TestHelper?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM