Java 如何将TestConfiguration放入抽象类中?

Java 如何将TestConfiguration放入抽象类中?,java,spring,spring-boot,Java,Spring,Spring Boot,我有一些Spring测试,它们都定义了相同的测试配置: @TestConfiguration public static class TestConfig { @Bean public EmployeeClient employeeClient(MockMvc mockMvc) { return new EmployeeClient(mockMvc); } } 为了减少复制,我将代码放入一个抽象类中

我有一些Spring测试,它们都定义了相同的测试配置:

    @TestConfiguration
    public static class TestConfig {
        @Bean
        public EmployeeClient employeeClient(MockMvc mockMvc) {
            return new EmployeeClient(mockMvc);
        }
    }
为了减少复制,我将代码放入一个抽象类中,并让每个测试扩展该抽象类。然而,这抛出了Spring未解析的依赖项—它无法解析
EmployeeClient


我如何才能做到这一点?

其中一种方法是让测试类使用多个配置文件

@Configuration
class CommonBeans {
}

@Configuration
class SpecificBeans {
}

@ContextConfiguration(classes = {CommonBeans.class, SpecificBeans.class}) 
public class MyAppTest {
  ------
}

在测试包中,如果使用@TestConfiguration而不是@configuration创建配置,则必须使用@Import注释来利用该配置

@TestConfiguration
public class TestBeans {
    
}

@Import(TestBeans.class)
public class MyAppTest {
      ------
}

谢谢,导入成功了。我应该使用
@Configuration
而不是
@TestConfiguration
吗?这完全取决于您的需求,只需了解它们之间的区别并做出决定即可。如果您的任何类都使用@SpringBootTest注释,那么它将自动扫描并为所有配置类创建bean,但您必须显式地导入TestConfiguration。你可以通过谷歌进一步了解。