【单元测试】加载配置文件实现单元测试

首先引入JUnit依赖,注意版本,很容易报错

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

找到web.xml,找到项目启动时加载的所有配置文件,复制路径,如下
tBibdI.png

然后添加一个test类,加上注解如下

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/config/application-context.xml",
        "classpath*:/config/application-context-sevice-mybatisPlus.xml",
        "classpath*:/config/spring-tuogangmq.xml",
        "classpath*:/config/kafka-consumer.xml",
        "classpath*:/config/kafka-producer.xml"})

接下来在该类里任意创建方法加上@Test即可愉快地测试了,也可以用注解任意引入项目中配置文件扫描到的组件,如下
tBFamd.png


关于SpringBoot的单元测试比较容易,SpringBoot默认会创建一个DemoApplicationTests类,只要新建测试类继承该类即可在测试中使用Spring容器组件