如何使用SpringApplicationConfiguration或ContextConfiguration加载较小的应用程序部分。

5
我正在开发一个基于spring-boot的项目,这对我来说是相当新的。目前,我使用@WebApplicationContext注解来运行任何JUnit测试,因为我似乎无法以其他方式启动应用程序。我的目标是要么得到一个明确的答案来避免使用它,要么获得链接到使用适用概念的项目。
我的确切目标是:我想要一个测试配置,它不会为了测试更小的服务和子类集而加载整个Web应用程序。
例如: 我目前有一系列3个装配器。其中一个是父对象的,另外两个是与子对象相关的。
@Component
public class ReportResponseAssembler {

    @Autowired
    private ParameterResponseAssembler parameterResponseAssembler;

    @Autowired
    private TimeRangeResponseAssembler timeRangeResponseAssembler;

    public ReportResponseAssembler makeResponse() {
        return new ReportResponseAssembler();
    }
}

为了测试目的,我希望只加载这三个类,并使它们适当地将依赖项注入父级。像这样的:

public class ReportResponseAssemblerTest {

    @Autowired
    ReportInstanceResponseAssembler reportResponseAssembler;

    @Test
    public void testPlaceHolder() {
        Assert.assertNotNull(reportResponseAssembler);
    }
}

我尝试了以下的做法:

@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.blahpackage.service.assembler" })
@Configuration
public class TestContextConfiguration {}

将此内容提供给SpringApplicationConfiguration,但即使进行了扫描,它仍无法检测到适用于自动注入的Bean。也许我需要在配置中直接标识它们为@Bean并返回新实例?是否有其他好的方法?如果您有示例项目或解释的链接,那就太好了。

感谢任何回复此帖的人,感谢您花费宝贵的时间。


在第一个代码片段中,您有ReportResponseAssembler,在第二个代码片段中是ReportInstanceResponseAssembler。这是打字错误吗? - a better oliver
2个回答

5

以下代码可以轻松实现您要做的事情:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestContextConfiguration.class)
public class ReportResponseAssemblerTest {

    @Autowired
    ReportInstanceResponseAssembler reportResponseAssembler;

    @Test
    public void testPlaceHolder() {
        Assert.assertNotNull(reportResponseAssembler);
    }
}

@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.blahpackage.service.assembler" })
@Configuration
public class TestContextConfiguration {

}

你提到的这三个类需要放在com.blahpackage.service.assembler下,并且还需要使用一些Spring的注解来进行标注,例如@Component或者@Service。例如:

@Component
public class ReportResponseAssembler {

    @Autowired
    private ParameterResponseAssembler parameterResponseAssembler;

    @Autowired
    private TimeRangeResponseAssembler timeRangeResponseAssembler;

    public ReportResponseAssembler makeResponse() {
        return new ReportResponseAssembler();
    }
}

@Component
public class ParameterResponseAssembler {
   //whatever
}

我建议您很少使用这样的测试,因为它会对性能产生影响。我的意思是,如果您有许多此类测试,Spring需要为每个测试创建和销毁不同的应用程序上下文,而如果您使用相同的上下文和测试,Spring可以(通常)缓存上下文。请查看这篇博客文章了解更多详情。


2

我建议完全不要创建测试配置。你的集成测试(希望你知道单元测试根本不应该创建Spring上下文)将会测试在生产中不使用的配置。

我建议为每个包/模块/集成测试单元创建一个Spring配置。然后,你可以通过@Import注释将这些配置导入其他上下文中。

按照包的方法有巨大的优势,你可以指定包私有(默认访问修饰符)的bean。

@Component
class SomeBeanClass{
}

这些只能由同一程序包内的bean自动装配,这是一种方便的方式来封装Spring bean。
这样细分的Spring配置可以很容易地在隔离中进行集成测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接