美文网首页
Spring 整合 junit 实现单元测试

Spring 整合 junit 实现单元测试

作者: SheHuan | 来源:发表于2020-01-05 22:47 被阅读0次

以访问 IoC 容器中的对象进行功能测试为例,单纯使用 junit 进行单元测试时,我们一般可以这样做:

public class AccountServiceTest {
    @Test
    public void transfer() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
        AccountService accountService = (AccountService) context.getBean("accountService");
        accountService.transfer(1, 2, 100);
    }
}

或者更好一些的做法:

public class AccountServiceTest {
    private AccountService accountService;

    @Before
    public void init(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
        accountService = (AccountService) context.getBean("accountService");
    }

    @Test
    public void transfer() {
        accountService.transfer(1, 2, 100);
    }

但这都避免不了我们手动创建 IoC 容器,以及从中获取对象。我们更希望的是拿掉这两步,可以用@Autowired完成对象的自动装配,以简化步骤,将重心放到功能的测试上,这就是我们接下来要了解的 Spring 整合 junit 实现单元测试。

首先,创建 Maven 项目,在 pom.xml 添加 junit 的 jar 包依赖,以及 Spring 整合 junit 的 jar 包依赖,

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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.23.RELEASE</version>
    <scope>test</scope>
</dependency>

需要注意的是,Spring 整合 junit 时,junit 的版本最好使用4.12及以上,否则可能会出现如下异常:

java.lang.ExceptionInInitializerError
......
......
Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher
......
......

接下来,编写单元测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BeanConfig.class})
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void transfer() {
        accountService.transfer(1, 2, 100);
    }
}

@RunWith(SpringJUnit4ClassRunner.class)是固定配置,作用是把 junit 提供的 main 方法替换成 Spring 提供的 main 方法。
@ContextConfiguration(classes = {BeanConfig.class})是用来加载创建 Spring IoC 容器的配置文件,这里加载的是基于注解的配置 Java 配置文件,当然也可以加载 xml 配置文件,例如:
@ContextConfiguration(locations = {"classpath:bean.xml"}),当然同时加载 Java 配置文件和 xml 配置文件也是没问题的。

到这里整合的工作就完成了,还是很简单的,我们只需要关心加载哪些 IoC 容器的配置文件,用@Autowired进行目标对象的自动装配即可,而不用考虑 IoC 容器的创建以及对象的获取。

相关文章

网友评论

      本文标题:Spring 整合 junit 实现单元测试

      本文链接:https://www.haomeiwen.com/subject/lygipctx.html