SpringBoot之添加单元测试

在SpringBoot里添加单元测试是非常简单的一件事,我们只需要添加SpringBoot单元测试的依赖jar,然后再添加两个注解就可搞定了。

首先我们来添加单元测试所需要的jar

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
接着我们写了一个单元测试的demo
package com.zkn.learnspringboot.service.test;

import com.zkn.learnspringboot.FirstExample;
import com.zkn.learnspringboot.service.PersonService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by wb-zhangkenan on 2016/11/18.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FirstExample.class)
public class TestService extends BaseTestService{
    @Autowired
    private PersonService personService;
    @Test
    public void testSys() {
        System.out.println(personService.getPersonDomain().toString());
    }

}
然后我们run一下,一个单元测试就搞定了。

另外:@RunWith和@SprintBootTest这两个注解上都有@Inherited这个注解,所以我们可以定义一个单元测的父类,然后所有的单元测试类继承这个父类就行了。如下所示:

package com.zkn.learnspringboot.service.test;

import com.zkn.learnspringboot.FirstExample;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by zkn on 2016/11/20.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FirstExample.class)
public class BaseTestService {

}
package com.zkn.learnspringboot.service.test;

import com.zkn.learnspringboot.service.PersonService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by wb-zhangkenan on 2016/11/18.
 */

public class TestService extends BaseTestService{
    @Autowired
    private PersonService personService;
    @Test
    public void testSys() {
        System.out.println(personService.getPersonDomain().toString());
    }

}
如果你用的SpringBoot是1.4.0之前的话,所用的注解稍有不同。你需要把@SpringBootTest注解换成@SpringApplicationConfiguration和@WebAppConfiguration。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值