单元测试体系(三)-controller单元测试例子

单元测试体系目录

序号 类型
1 单元测试体系(一)-什么是单元测试?
2 单元测试体系(二)-快速生成单元测试目录结构(eclipse)
3 单元测试体系(三)-controller单元测试例子
4 单元测试体系(四)-service单元测试例子
5 单元测试体系(五)-mapper单元测试例子(MyBatis)
6 单元测试体系(六)-异常模块


单元测试体系(三)-controller单元测试例子

工具: eclipse
项目类型: springBoot

junit常用注解

junit常用注解
@Test(timeout = 10)
测试,该注解必须加到方法上
timeout超时时间,单位是毫秒
终止死循环,当达到设定的值,结束循环
@Ignore
忽略不想被测试的方法,该注解必须加到方法上,也可以加到类上(慎用)
@RunWith(SpringJUnit4ClassRunner.class)
把junit和spring整合到一块,该注解加到类上
@ContextConfiguration(locations = {“classpath:conf/applicationContext.xml”})
用于加载spring配置文件的注解,添加到类上
locations代表spring配置文件路径的数组,数组的类型为Stirng
classpath:这个东西代表从源包下开始寻找
@Resource(name = “blogService”)
注入属性的注解,就相当于set、get方法,name指明bean的id值
@Before
在所有方法之前执行,一般加到方法上
@After
在所有方法之后执行,一般加到方法上
@Transactional
@TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
上边这俩注解要一块用,用于事物控制,加到类上
transactionManager代表配置文件中事务管理器bean的id值
defaultRollback代表事物回滚,默认值为true,是回滚的


assert常用方法

Assert.assertEquals(“message”,A,B):
判断对象A和B是否相等,这个判断比较时调用了equals()方法。
Assert.assertSame(“message”,A,B):
判断对象A和B是否相同,使用的是==操作符。
Assert.assertTure(“message”,A):
判断A条件是否为真。
Assert.assertFalse(“message”,A):
判断A条件是否不为真。
Assert.assertNotNull(“message”,A):
判断A对象是否不为null
Assert.assertArrayEquals(“message”,A,B):
判断A数组与B数组是否相等。


公用注解

@WebMvcTest
主要用于controller层测试,只覆盖应用程序的controller层,HTTP请求和响应是Mock出来的,因此不会创建真正的连接。因此需要创建 MockMvc bean进行模拟接口调用
@RunWith(SpringRunner.class)
@RunWith(SpringJUnit4ClassRunner)
是Junit和Spring Boot test联系的桥梁
@Slf4j
日志


MockMvc(controller层单元测试运用:)

① perform
perform(RequestBuilder requestBuilder) throws Exception
执行请求,需要传入 MockHttpServletRequest 对象【请求对象】
② andDo
andDo(ResultHandler handler) throws Exception
执行普通处理,例如 MockMvcResultHandlers的print() 方法用于 打印请求、响应及其他相关信息
③ andExpect
andExpect(ResultMatcher matcher) throws Exception
执行预期匹配,例如:
MockMvcResultMatchers.status().isOk() 预期响应成功
MockMvcResultMatchers.content().string(final String expectedContent) 指定预期的返回结果内容[字符串]
MockMvcResultMatchers.content().contentType(String contentType) 指定预期的返回结果的媒体类型
MockMvcResultMatchers.forwardedUrl(final String expectedUrl) 指定预期的请求的URL链接
MockMvcResultMathcers.redirectedUrl(final String expectedUrl) 指定预期的重定向的URL链接
注意:当有一项不满足时,则后续就不会进行。
④ andReturn
andReturn()
返回 MvcResult [请求访问结果]对象
⑤ getRequest
getRequest()
返回 MockHttpServletRequest [请求]对象

例子:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest(classes=CustomizedShanxiApplication.class)
@Slf4j
public class TestQueryControllerTest {
    private TestQueryVo aggregateQueryVo;
    //日志信息
    private  static String DY_MSG = "";
         
    private final static String DY_MSG1 = "单元测试【TestQueryControllerTest】 FdQuery";
    private MockMvc mockMvc;
    static{
              DY_MSG = DY_MSG1 ;
       }
    @Autowired
    private TestQueryController aggregateQueryController;
   
    @Before
    public void setUp() throws Exception {
        log.info("{}--start!!!!",DY_MSG);
        mockMvc = MockMvcBuilders.standaloneSetup(aggregateQueryController).build();
        @SuppressWarnings("resource")
        Scanner s = new Scanner(System.in);
        String  g = s.next().toString();
        aggregateQueryVo = new TestQueryVo();
        aggregateQueryVo.setTradeDate(g);
    }
       @Test
       public void testFdQuery() throws Exception {
            Gson gson = new Gson();
           
            String json = gson.toJson(aggregateQueryVo);
            MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/aggregateQuery/fdQuery")//使用post方式来调用接口。
                .contentType(MediaType.APPLICATION_JSON)//请求参数的类型
                .param(json)//请求的参数(可多个)
                 ).andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
           
          //获取数据
           JSONObject jsonObject =new  JSONObject(result.getResponse().getContentAsString());
           JSONArray jsonArrayData = (JSONArray)jsonObject.get("data");
           ///加断言,判断属性值
       }
       
        /**
    *
    * 结束
    * @author yangzhenyu
    * @date 2020/08/18
    *
    * */
      @After
      public void after(){
            log.info("{}--end!!!!",DY_MSG);
      }
}

猜你喜欢

转载自blog.csdn.net/weixin_38316697/article/details/108196348