spring boot:單元測試mockito

1.     Pom添加依賴包

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-test</artifactId>

       </dependency>

       <dependency>

           <groupId>com.jayway.jsonpath</groupId>

           <artifactId>json-path</artifactId>

       </dependency>

2.     測試Controller

/**

* AuthControllerTests.java

* Created at 2017年11月30日

* Created by hurf

* Copyright (C) 2017 XXX, All rights reserved.

*/

package com.svw.tbox.tcloud.security.auth.controller;

 

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

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

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

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

 

import java.util.LinkedHashMap;

 

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.http.MediaType;

import org.springframework.test.context.ActiveProfiles;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;

 

import com.svw.tbox.tcloud.commons.util.JSONUtil;

import com.svw.tbox.tcloud.commons.web.Result;

import com.svw.tbox.tcloud.security.auth.AuthApplication;

 

/**

 * <p>ClassName: AuthControllerTests</p>

 * <p>Description: 測試auth服務</p>

 * <p>Author: hurf</p>

 * <p>Date: 2017年11月30日</p>

 */

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes = AuthApplication.class) // 這裏的Application是springboot的啓動類名。

@WebAppConfiguration("server.port:0") // 當前的測試是集成測試 ,隨機生成端口號 @Value("${local.server.port}")獲取生成的端口號

@ActiveProfiles("local") //測試本地分支

public class AuthControllerTests {

 

         @Autowired

         private WebApplicationContext context;

         private MockMvc mockMvc;

        

    @Value("${server.port}")

    private int port;

   

         @Before

         public void setupMockMvc() {

                  mockMvc = MockMvcBuilders.webAppContextSetup(context).build();

         }

 

//     private TestRestTemplate restTemplate = new TestRestTemplate();

        

         @Test

    public void login() throws Exception {

//              Result result = restTemplate.getForObject("http://localhost:" + port +"/login/hrfhrf3210/mm-123", Result.class);

                  MvcResult result = mockMvc

                  .perform(get("/login/hrfhrf3210/mm-123").accept(MediaType.APPLICATION_JSON_UTF8))

                  .andExpect(status().isOk())

                  .andReturn();

                 

                  Result rs = JSONUtil.toBean(result.getResponse().getContentAsString(), Result.class) ;

                  String token = JSONUtil.toBean(rs.getContent().toString(),LinkedHashMap.class).get("accessToken").toString();

                  System.out.println(token);

    }

        

         /**

          *

          * <p>Title: 根據上一步登錄打印的accessToken做參數測試</p>

          * <p>Description: </p>

          * @throws Exception

          */

         @Test

    public void logout() throws Exception {

                  mockMvc

                  .perform(delete("/logout").header("accessToken", "login-return-access-token").accept(MediaType.APPLICATION_JSON_UTF8))

                  .andExpect(status().isOk());

    }

        

         /**

          *

          * <p>Title: 根據登錄打印的refreshToken做參數測試</p>

          * <p>Description: </p>

          * @throws Exception

          */

         @Test

    public void token() throws Exception {

                  mockMvc

                  .perform(put("/logout").header("refreshToken", "login-return-refresh-token").accept(MediaType.APPLICATION_JSON_UTF8))

                  .andExpect(status().isOk());

    }

}

1.    Lombok簡化開發POJO/VO

1.     IDE要安裝Lombok插件

1.     STS(eclipse)安裝

下載lombok.jar : https://projectlombok.org/downloads

雙擊lombok.jar 下一步到 選中 eclipse.ini文件 或者sts.exe,單擊install/update

重啓

2.     Idea安裝

在prefrences->plugins中搜索lombok plugin安裝就可以

2.    分頁

1.     添加依賴

       <dependency>

           <groupId>com.github.pagehelper</groupId>

           <artifactId>pagehelper-spring-boot-starter</artifactId>

           <version>1.1.0</version>

           <exclusions>

              <exclusion>

                  <artifactId>tomcat-jdbc</artifactId>

                  <groupId>org.apache.tomcat</groupId>

              </exclusion>

           </exclusions>

       </dependency>

2.     封裝

package com.svw.tbox.tcloud.commons.controller;

 

import java.util.List;

 

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;

import com.svw.tbox.tcloud.commons.vo.PageRequest;

 

/**

 * @Title <p>ClassName: PageController</p>

 * @Description <p>Description: 分頁相關控制類</p>

 * @Author <p>Author: hurf</p>

 * @Date <p>Date: 2018年1月11日</p>

 */

public class PageController {

        

         /**

          * @Title <p>Title: 分頁</p>

          * @Description <p>Description:獲取指定頁數據 </p>

          * @param pageNo 當前頁號

          * @param pageSize 每一頁數量

          * @param objects 所有數據列表

          * @return 當前頁數據

          */

         protected <T> PageInfo<T> filterByPage(int pageNo, int pageSize, List<T> objects) {

                  PageRequest page = new PageRequest(pageNo, pageSize);

                  PageHelper.startPage(page.getPageNow(), page.getPageSize());

                  return new PageInfo<>(objects);

         }

}

3.     使用

    @ApiOperation(value = "根據用戶代碼查詢用戶信息")

    @ApiImplicitParams({

           @ApiImplicitParam(name = "uid", value = "用戶代碼(複數必須用英文逗號,連接)", paramType = "path", required = true),

           @ApiImplicitParam(name = "pageNo", value = "當前頁", paramType = "path", required = true),

           @ApiImplicitParam(name = "pageSize", value = "每頁記錄數", paramType = "path", required = true) })

    @RequestMapping(value = "/queryUserInfo/{uid}/{pageNo}/{pageSize}", method = RequestMethod.GET)

    public SystemResponse queryUserInfo(@PathVariable("uid") String uid, @PathVariable("pageNo") intpageNo,

           @PathVariable("pageSize") intpageSize) {

       String[] uids = uid.split(",");

       List<String> uidList = Arrays.asList(uids);

       List<UserInfoVo> userInfoVos = tmAccountService.queryUserInfo(uidList);

       PageInfo<UserInfoVo> ms = filterByPage(pageNo, pageSize, userInfoVos);

       return ResultUtil.success(ms);

    }

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章