如何在IDEA中对于SpringBoot项目快速创建单元测试

创建测试用例

右键需要进行测试的方法,选择GO TO然后选择Test

点击Create New Test

勾选需要创建单元测试的方法

然后点击OK就直接创建完成了。

修改测试用例

在类上面加上注解

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
然后在下面注入需要测试的类然后在方法里面使用,使用方法和普通的单元测试一样
如果测试的是service
demo如下
package com.example.demo;

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; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class HelloServiceTest { @Autowired
private HelloService helloService; @Test
public void hello(){
helloService.hello();
} }

如果测试的是controller

需要加入@AutoConfigureMockMvc的注解

那么demo如下

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest { @Autowired
private MockMvc mockMvc; @Test
public void hello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
.andExpect(MockMvcResultMatchers.status().isOk());
} }

其中对于MockMvc的使用可以自己研究一下,里面有很多测试使用的东西,这边只是举个例子,只要访问是200不是404这种错误都会过测试用例

最新文章

  1. php实现显示网站运行时间-秒转换年月日时分秒
  2. Codeforces Round #249 (Div. 2) D. Special Grid 枚举
  3. Bluetooth
  4. javascript 写职责链
  5. LANG=C是最早最简单的C语言环境(标准ASCII码)
  6. 命运(HDU 2571 简单动态规划)
  7. iOS 的三种自建证书方法https请求相关配置
  8. css清除浮动float的三种方法总结
  9. Java 单元测试 JUnit4 快速入门
  10. git基础命令学习总结
  11. Svn基本操作
  12. 【转帖】Linux的历史----Linux内核剖析(一)
  13. ARC设置
  14. 5、JDBC-元信息
  15. 延续(continuation)
  16. mongodb 通过mongodump来备份Sharded Cluste分片集群
  17. Oracle EBS 清理归档
  18. Sql Server 优化技巧
  19. Hadoop NameNode HA 和 ResourceManager HA
  20. Word中如何公式居中标号右对齐

热门文章

  1. 机器学习(二)--------单变量线性回归(Linear Regression with One Variable)
  2. mybatis进阶--一对多查询
  3. 使用RabbitMq
  4. Python中删除easy_install安装的包
  5. spring中aop事务
  6. 序列化与Json
  7. VIBE(前景检测)
  8. C#使用iTextSharp+ZXing.Net+FreeSpire.PDF生成和打印pdf文档
  9. JVM活学活用——调优工具
  10. Sequential Container