1、需要导入的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--这里是你要加的依赖-->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
2、创建测试文件夹
3、打开我们编写好的service类
在该类里面,ctrl+shift+T组合键,生成对应的单元测试类
单击OK键,自动生成
4、修改生成的测试类
import com.thread.service.PurchaseService;
import org.junit.Assert;
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;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PurchaseServiceImplTest {
@Autowired
PurchaseService purchaseService = null;
@Test
public void purchase() {
// Assert.assertEquals(Integer.valueOf(1),purchaseService.purchase(1L,1L,1));
Assert.assertNotNull(purchaseService.purchase(1L,1L,1));
}
}
单击左侧这两个按钮,即可执行测试方法
注意,@Test注解的包别导错了:org.junit.Test
5、测试restful接口
@RunWith(SpringRunner.class)
/*测试restful接口的时候,使用随机端口测试服务*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT )
public class RestFulTest {
/*REST测试模板,Spring Boot自动提供*/
@Autowired
private TestRestTemplate restTemplate;
@Test
public void getUser(){
/*请求当前启动的项目,请注意URI的缩写,没有指定IP和PORT*/
User user = this.restTemplate.getForObject("/user/{id}", User.class, 1);
System.out.println("user:"+user.getUserName());
Assert.assertNotNull(user);
}
}
注意和上面的区别
参考:
https://blog.csdn.net/lansexiuzhifu/article/details/81413477 错误情况1解决方法
https://blog.csdn.net/weixin_46399870/article/details/104486572 错误情况2解决办法
https://www.jianshu.com/p/72b19e24a602 实例