SpringBoot从Controller层怎么进行单元测试

这篇文章主要讲解了Spring Boot从Controller层怎么进行单元测试,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

10年积累的网站设计、成都网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有隆回免费网站建设让你可以放心的选择与我们合作。

单元测试是程序员对代码的自测,一般公司都会严格要求单元测试,这是对自己代码的负责,也是对代码的敬畏。

一般单元测试都是测试Service层,下面我将演示从Controller层进行单元测试。

无参Controller单元测试示例:

package com.pingan.bloan.genesis.controller.base;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import com.pingan.bloan.genesis.logwrapper.LogWrapper;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.pingan.bloan.genesis.logwrapper.LogWrapperFactory;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class BaseSpringBootTest {
  protected LogWrapper logger = LogWrapperFactory.getLogWrapper(BaseSpringBootTest.class);
  
  @Before
  public void init() {
    logger.info("开始测试...");
  }
  
  @After
  public void after() {
    logger.info("测试结束...");
  }
}
package com.pingan.bloan.genesis.controller;

import org.junit.Test;
import org.junit.Before;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.pingan.bloan.genesis.controller.base.BaseSpringBootTest;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

/**
 * DemoController测试
 * @author 
 *
 */
public class DemoControllerTest extends BaseSpringBootTest {
  @Autowired
  private DemoController demoController;
  
  private MockMvc mockMvc;
  
  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(demoController).build();
  }
  
  @Test
  public void demo() throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/demo/demo"))
                   .andExpect(MockMvcResultMatchers.status().isOk())
                   .andDo(MockMvcResultHandlers.print())
                   .andReturn();

    logger.info(mvcResult.getResponse().getContentAsString());
  }
}

有参Controller单元测试示例一:

package com.pingan.bloan.genesis.controller;

import org.junit.Test;
import org.junit.Before;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.pingan.bloan.genesis.controller.base.BaseSpringBootTest;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

/**
 * 加解密controller测试
 * 
 * @author 
 *
 */
public class MessageEncryptionControllerTest extends BaseSpringBootTest {
  @Autowired
  private MessageEncryptionController messageEncryptionController;
  
  private MockMvc mockMvc;
  
  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(messageEncryptionController).build();
  }
  
  /**
   * 加密测试
   * @throws Exception 
   */
  @Test
  public void encryption() throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/secret/encryption")
                   .accept(MediaType.APPLICATION_JSON).param("originContent", "15221365094"))
                   .andExpect(MockMvcResultMatchers.status().isOk())
                   .andDo(MockMvcResultHandlers.print())
                   .andReturn();
    
    logger.info(mvcResult.getResponse().getContentAsString());
  }
  
  /**
   * 解密测试
   * @throws Exception 
   */
  @Test
  public void deciphering() throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/secret/deciphering")
                   .accept(MediaType.APPLICATION_JSON).param("secretContent", "4BD6EE1A13593F97E6CEA20A2BA9E6E4"))
                   .andExpect(MockMvcResultMatchers.status().isOk())
                   .andDo(MockMvcResultHandlers.print())
                   .andReturn();

    logger.info(mvcResult.getResponse().getContentAsString());
  }
}

有参Controller单元测试示例二:

package com.pingan.bloan.genesis.controller;

import org.junit.Test;
import org.junit.Before;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.pingan.bloan.genesis.controller.base.BaseSpringBootTest;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.pingan.bloan.genesis.model.mobiletelephone.MobileTelephoneRequest;

/**
 * 客户手机掩码信息加密处理测试
 * @author 
 *
 */
public class MobileTelephoneIdempotentControllerTest extends BaseSpringBootTest {
  @Autowired
  private MobileTelephoneIdempotentController mobileTelephoneIdempotentController;
  
  private MockMvc mockMvc;
  
  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(mobileTelephoneIdempotentController).build();
  }
  
  /**
   * 保存加密处理的客户信息
   * @throws Exception 
   */
  @Test
  public void saveCustomerEncryptionMessage() throws Exception {
    MobileTelephoneRequest request = new MobileTelephoneRequest();
    request.setCustomerId("RL20180304000099");
    request.setMobileTelephone("18883270484");
    request.setCcfMobileTelephone("13904108866");
    
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/customerEncryption/save")
                   .contentType(MediaType.APPLICATION_JSON)
                   .content(JSONObject.toJSONString(request)))
                   .andExpect(MockMvcResultMatchers.status().isOk())
                   .andDo(MockMvcResultHandlers.print())
                   .andReturn();
    
    logger.info(mvcResult.getResponse().getContentAsString());
  }
}

Suite一次性执行多个单元测试:

package com.pingan.bloan.genesis.controller;

import org.junit.runners.Suite;
import org.junit.runner.RunWith;

/**
 * 打包测试
 * 配置测试类,一次性执行所有配置的测试类
 * @author 
 *
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({MessageEncryptionControllerTest.class, DemoControllerTest.class})
public class SuiteExecuteTests {
  // 不用写代码,只需要注解即可(在SuiteClasses中配置测试类)
}

代码单元测试,让代码更加健壮。

看完上述内容,是不是对Spring Boot从Controller层怎么进行单元测试有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。


本文标题:SpringBoot从Controller层怎么进行单元测试
文章URL:http://scjbc.cn/article/gdijdj.html

其他资讯