<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>spring-boot-junitgroupId>
<artifactId>spring-boot-junitartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.7.RELEASEversion>
<relativePath/>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
dependencies>
project>
@Controller
@RequestMapping(value = "/junit")
public class JunitTestController {
@Autowired
private JunitService junitService;
@RequestMapping(value = "/helloJunit")
public ModelAndView helloJunit() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", junitService.junitTestServiceString("Frank"));
modelAndView.setViewName("index");
return modelAndView;
}
}
import com.frank.sb.junit.JunitApplication;
import org.junit.Assert;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JunitApplication.class)
@WebAppConfiguration
public class JunitTestControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
@Before
public void setUp()throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void helloJunit() throws Exception{
/**
* 1、mockMvc.perform执行一个请求。
* 2、MockMvcRequestBuilders.get("XXX")构造一个请求。
* 3、ResultActions.param添加请求传值
* 4、ResultActions.accept(MediaType.TEXT_HTML_VALUE))设置返回类型
* 5、ResultActions.andExpect添加执行完成后的断言。
* 6、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
* 比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
* 5、ResultActions.andReturn表示执行完成后返回相应的结果。
*/
MvcResult mvcResult= mvc.perform(MockMvcRequestBuilders.get("/junit/helloJunit")
// 参数传递
// .param("name","lvgang")
.accept(MediaType.TEXT_HTML_VALUE))
// .andExpect(MockMvcResultMatchers.status().isOk()) //等同于Assert.assertEquals(200,status);
// .andExpect(MockMvcResultMatchers.content().string("hello lvgang")) //等同于 Assert.assertEquals("hello lvgang",content);
.andDo(MockMvcResultHandlers.print())
.andReturn();
int status=mvcResult.getResponse().getStatus(); //得到返回代码
String content=mvcResult.getResponse().getContentAsString(); //得到返回结果
Assert.assertEquals(200,status); //断言,判断返回代码是否正确
Assert.assertEquals("你好:Frank",content); //断言,判断返回的值是否正确
}
}
...
...
...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2019-09-15 19:36:40.602 INFO 4068 --- [ main] c.f.s.j.c.JunitTestControllerTest : Starting JunitTestControllerTest on DESKTOP-4E4GNBT with PID 4068 (started by cy880 in E:\Project\Java\spring-boot-frank\spring-boot-junit)
2019-09-15 19:36:40.603 INFO 4068 --- [ main] c.f.s.j.c.JunitTestControllerTest : No active profile set, falling back to default profiles: default
2019-09-15 19:36:41.758 INFO 4068 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-15 19:36:41.831 INFO 4068 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2019-09-15 19:36:42.062 INFO 4068 --- [ main] c.f.s.j.c.JunitTestControllerTest : Started JunitTestControllerTest in 1.817 seconds (JVM running for 2.516)
2019-09-15 19:36:42.222 INFO 4068 --- [ main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2019-09-15 19:36:42.223 INFO 4068 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2019-09-15 19:36:42.232 INFO 4068 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 9 ms
sign in service impl ------
MockHttpServletRequest:
HTTP Method = GET
Request URI = /junit/helloJunit
Parameters = {}
Headers = [Accept:"text/html"]
Body =
Session Attrs = {}
Handler:
Type = com.frank.sb.junit.controller.JunitTestController
Method = public org.springframework.web.servlet.ModelAndView com.frank.sb.junit.controller.JunitTestController.helloJunit()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = index
View = null
Attribute = msg
value = 你好:Frank
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Language:"en", Content-Type:"text/html;charset=UTF-8"]
Content type = text/html;charset=UTF-8
Body = 你好:Frank
Forwarded URL = null
Redirected URL = null
Cookies = []
2019-09-15 19:36:42.324 INFO 4068 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Disconnected from the target VM, address: '127.0.0.1:64469', transport: 'socket'
Process finished with exit code 0
通过观察单元测试类,用到了一个关键类(MockMvcRequestBuilders)用来构建请求,下面简单下它的关键API:
MockHttpServletRequestBuilder可通过方法获取两类Builder (MockHttpServletRequestBuilder、MockMultipartHttpServletRequestBuilder ),下面分别介绍两类的主要API:
MockMultipartHttpServletRequestBuilder继承自MockHttpServletRequestBuilder
MockMvc.perform(RequestBuilder requestBuilder)后将得到ResultActions,通过ResultActions完成如下三件事
ResultMatcher用来匹配执行完请求后的结果验证,其就一个match(MvcResult result)断言方法,如果匹配失败将抛出相应的异常;此类例子中并没有使用,具体提供以下API:
博客API内容转自:https://my.oschina.net/sdlvzg/blog/1594821
GitHub 项目地址