SpringBoot Unit Test入门

    xiaoxiao2024-10-24  94

    1. Junit工作原理

    使用JUnit测试,不用自己在测试类中写很多main函数测试。

    单元测试返回值都为空(public void)。单元测试通过的标准(满足下面其中一个条件即可):

    a)测试方法运行完没有抛出异常. 

    b)测试方法抛出的异常,和“expect”定义的异常一致

    当满足标准, Eclipse自动判断测试通过。

     

    2 Unit Test  in SpringBoot

    用如下注解修饰测试类

    @RunWith(SpringRunner.class)   //运行测试的类。 不写这个的情况下,会//直接用JUnit去跑。 SpringRunner是JUnit的扩展 @SpringBootTest  //可以加测试的参数,如端口 @AutoConfigureMockMvc  // 测试RestAPI的时候会用到。 封装了TestRestTemplate的相关功能

    package com.github.binarywang.demo.wx.mp.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class WxPortalControllerTest { @Autowired private MockMvc mockMvc; @Test public void testAuthGet() throws Exception { this.mockMvc .perform(get("/wx/portal/wx23bb34a1ff46582d") .param("signature", "93d0ef82f9e01a94971d2fb4eb6aca61f29509aa").param("timestamp", "1558536215") .param("nonce", "9874674366").param("echostr", "dfdkasjdfaskdjf")) .andDo(print()).andExpect(status().isOk()).andExpect(content().string("dfdkasjdfaskdjf")); ; } }

     

    2.1 测试Service层

    2.2 测试Controller层

    通过MockMvc类去触发api

    a)perfrom()的参数是要创建一个Request

    通过MockMvcRequestBuilders 去创建,get()其实是MockMvcRequestBuilders.get().因为import了这个类,所以可以简写

    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

     

    get()返回的是MockHttpServletRequestBuilder. MockHttpServletRequestBuilder.param())是为了创建Request,所以它返回的依然是MockHttpServletRequestBuilder,所以,假如有多个参数,可以直接用多个param()方法引入

    b)Perform()的返回值是ResultActions

    ResultActions.andExcept()用于判断运行结果,起到断言的作用。 它的参数是MockMvcResultMatchers。通过

    MockMvcResultMatchers.status()判断返回值

    MockMvcResultMatchers.content(),获取response content的属性/内容去比较

    返回值为string是

    andExpect(content().string("dfdkasjdfaskdjf"))

    ??返回值为Json

    andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Mock测试2"))

    比较返回值contenttype

    .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))

     

    另外一种情况是通过ResultActions.andReturn(),返回一个MvcResult,用其他断言去比较返回结果

     

     

    参考文章

    https://www.cnblogs.com/ysocean/p/6889906.html

    https://www.jianshu.com/p/72b19e24a602

    https://www.jianshu.com/p/91045b0415f0

    最新回复(0)