Spring Boot從Controller層進行單元測試

單元測試是程序員對代碼的自測,通常公司都會嚴格要求單元測試,這是對本身代碼的負責,也是對代碼的敬畏。程序員

通常單元測試都是測試Service層,下面我將演示從Controller層進行單元測試。web

無參Controller單元測試示例:spring

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單元測試示例一:json

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單元測試示例二:mvc

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一次性執行多個單元測試:app

 

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中配置測試類)
}

 代碼單元測試,讓代碼更加健壯。post

相關文章
相關標籤/搜索