SpringBoot整合Junit测试
场景
相关项目搭建参照:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/column/info/35688
实现
在项目的pom/xml中添加测试依赖
![Image 1][]
<!-- springBoot整合测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
在controller包下新建要进行测试的controller。
SpringController
package com.example.demo.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class SpringController {
@RequestMapping("/test")
@ResponseBody
public String yes() {
return "test";
}
public static void main(String[] args) {
SpringApplication.run(SpringController.class, args);
}
}
在test包下新建testController
![Image 1][]
代码
package com.badao.test;
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;
import org.springframework.test.context.web.WebAppConfiguration;
import com.example.demo.controller.SpringController;
import junit.framework.TestCase;
@SpringBootTest(classes=SpringController.class)//要测试谁
@RunWith(SpringJUnit4ClassRunner.class) //指明进行测试的类
@WebAppConfiguration //指明和Web的整合
public class TestController {
@Autowired
private SpringController springController;
@Test
public void test1() {
TestCase.assertEquals(this.springController.yes(),"test");
}
}
这里使用断言比较返回值是否相等。
右键运行测试类
![Image 1][]
可以看到测试结果两个值相等。
![Image 1][]
源码下载:
https://download.csdn.net/download/badao_liumang_qizhi/11055983
[Image 1]:
还没有评论,来说两句吧...