Spring Boot (四十五)——使用单元测试

1、在pom文件中添加依赖


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

2、约定写法

单元测试代码写在src/test/java目录下。
单元测试类命名为*Test,前缀为要测试的类名。

3、@SpringBootTest注解的作用

  • @SpringBootTest替代了spring-test中的@ContextConfiguration注解,目的是加载ApplicationContext,启动spring容器。

  • 使用@SpringBootTest时并没有像@ContextConfiguration一样显示指定locations或classes属性,原因在于@SpringBootTest注解会自动检索程序的配置文件,检索顺序是从当前包开始,逐级向上查找被@SpringBootApplication或@SpringBootConfiguration注解的类。

4、Service测试

对于service层的测试比较简单,直接自动注入就可以测试:
service:

@Service
public class HelloService {

    public String sayHello(){
        return "hello service";
    }
}

测试类:

@SpringBootTest
class DevtoolsApplicationTests {
    @Autowired
    HelloService helloService;

    @Test
    void test() {
        String str = helloService.sayHello();
        System.out.println(str);
    }
}
5、Controller及Json测试

在Springboot中对Controller和Json测试比较不常用,也比较麻烦,一般我们使用浏览器和Postman进行测试非常方便,这里就不赘述了,百度一下吧。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值