1.首先导入依赖,junit的普通使用以及springboot的整合都可以使用这一套依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.普通使用
@Test
public void CommonUse() {
System.out.println("this is a common method");
}
它的特点是不能使用spring的相关功能,比如注解,框架等,但是对于普通的代码块是可以使用的,有时候我们junit5不能运行,需要调整到junit4,在run as → run config调整至junit4 ,
3.springboot 整合junit使用,示例代码如下:
package com.example.demo.createtest;
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.SpringRunner;
/*Springboot测试类
* @Runwith:启动器
* SpringJUnit4ClassRunner.class 让junit与spring环境进行整合
*
* @SpringBootTest
* 1.声明当前类为springboot的测试类
* 2.加载springboot的启动类,启动spring boot
* */
import com.example.demo.RabbitMqDemoApplication;
import com.example.demo.dao.UserMapper;
import com.example.demo.model.User;
@RunWith(SpringRunner.class)//idea似乎不需要这个注解
@SpringBootTest(classes = {RabbitMqDemoApplication.class})
public class SpringbootTest {
@Autowired
private UserMapper userMapper;
@Test
public void test_1() throws InterruptedException {
System.out.println("come in");
User sel = userMapper.Sel(1);
System.out.println("xxxxxxxxxx"+sel.toString());
Thread.sleep(20000);
}
}
需要注意的是需要在类前面添加注解@Runwith和@SpringBootTest,@SpringBootTest里面的为该项目的启动类,这样的话就可以运行注解等和spring相关的功能,运行方法同普通使用的方法
3.一些使用问题
光标要落在方法名上面,右击运行,而不是在别的地方,如:
-
程序包org.junit不存在
这是引用出了问题,而已把导入junit包的语句放在最前面,就会发现一些包出现了错误,然后ctrl+shift+o吧所有包重新导一下,也可以把所有的导包语句删掉,快捷键重新导包。 -
@MockBean注解使用 (其实就相当于一个挡板,对于未实现,或者很难调用的,做一个虚拟返回值)
在实际开发中,我们自己写的Controller、Service很可能去调用别的同事或别的项目组写的Service、Mapper,对方可能只写了一个接口,没有实现(比如本例中我写的Mapper),这样是没法进行测试的。
Mock的作用:创建一个虚拟的对象替代那些不易构造或不易获取的对象。
- eclipse测试方法的快捷使用
- IDEA测试方法的快捷使用
其实这种快速创建测试元的,也只是生成了一个方法而已,具体代码,还需要具体填写。