Spring Boot (四十五)——使用单元测试
发布日期:2021-05-07 10:02:45 浏览次数:16 分类:技术文章

本文共 941 字,大约阅读时间需要 3 分钟。

1、在pom文件中添加依赖

org.springframework.boot
spring-boot-starter-test
test

2、约定写法

单元测试代码写在src/test/java目录下。

单元测试类命名为*Test,前缀为要测试的类名。

3、@SpringBootTest注解的作用

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

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

4、Service测试

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

service:

@Servicepublic class HelloService {       public String sayHello(){           return "hello service";    }}

测试类:

@SpringBootTestclass DevtoolsApplicationTests {       @Autowired    HelloService helloService;    @Test    void test() {           String str = helloService.sayHello();        System.out.println(str);    }}

5、Controller及Json测试

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

上一篇:Redis (二)——Redis简介
下一篇:Spring Boot (四十四)——在idea中实现热部署

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月05日 00时48分51秒