1. 程式人生 > >在SpringMVC利用MockMvc進行單元測試

在SpringMVC利用MockMvc進行單元測試

轉自 http://www.cnblogs.com/wql025/p/5022395.html

----------------------------------------------------------------------------------------------------------------

一、應用示例

複製程式碼
package com.springapp.mvc;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration("file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml") public class AppTests { private MockMvc mockMvc; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired protected WebApplicationContext wac; @Before public void setup() { this.mockMvc = webAppContextSetup(this.wac).build();//獲取mockMvc例項 } @Test public void simple() throws Exception { mockMvc.perform(post("/mytest"))//執行一個RequestBuilder請求 .andExpect(view().name("index2"))//驗證返回檢視是否是"index2" .andDo(print()).andExpect(status().isOk());//列印結果到控制檯 } }
複製程式碼

二、程式碼解釋

@WebAppConfiguration

@WebAppConfiguration is a class-level annotation that is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext.

其中文意思是:“@webappconfiguration是一級註釋,用於宣告一個ApplicationContext整合測試載入WebApplicationContext。

private MockMvc mockMvc;

Main entry point for server-side Spring MVC test support.

其中文意思是:對於伺服器端的Spring MVC測試支援主入口點。

該物件可以由方法webAppContextSetup(WebApplicationContext context).build()構造。

org.springframework.test.web.servlet.setup.MockMvcBuilders

先介紹些:MockMvcBuilder,MockMvcBuilder是用來構造MockMvc的構造器,其主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分別對應之前的兩種測試方式。對於我們來說直接使用靜態工廠MockMvcBuilders建立即可(注:MockMvcBuilders在官方文件中並未找到):

MockMvcBuilders.webAppContextSetup(WebApplicationContext context):指定WebApplicationContext,將會從該上下文獲取相應的控制器並得到相應的MockMvc

MockMvcBuilders.standaloneSetup(Object... controllers):通過引數指定一組控制器,這樣就不需要從上下文獲取了。

simple方法中的程式碼中的方法:

perform:執行一個RequestBuilder請求,會自動執行SpringMVC的流程並對映到相應的控制器執行處理;

andExpect:新增ResultMatcher驗證規則,驗證控制器執行完成後結果是否正確;

andDo:新增ResultHandler結果處理器,比如除錯時列印結果到控制檯;

後記:更多參加spring的官方文件

附:另一種測試

複製程式碼
package com.spring.test;

import com.wql.dao.UserMapper;
import com.wql.vo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Created by Administrator on 15-12-11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class SqlTests {
    @Resource
    private UserMapper userMapper;

    @Test
    public  void test(){
        User u =  userMapper.selectByPrimaryKey(1);
        System.out.println(u);
    }

    @Test
    public void test2(){
        User u = new User();
        u.setName("wang");
        u.setPassword("112");
        System.out.println(userMapper.checkLogin(u));
    }

}
複製程式碼

相關推薦

SpringMVC利用MockMvc進行單元測試

轉自 http://www.cnblogs.com/wql025/p/5022395.html --------------------------------------------------------------------------------------

springMVC整合Junit4進行單元測試

main方法 pri tail println test pan ati 測試的 tco 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 用Junit做單元測試的好處多多,博主領悟到了兩點。一是不用在每個類裏面都寫main方法然後去測試;二是可以得到每個方法執行

用flask開發個人部落格(28)—— 利用unittest進行單元測試

下面分析下這個webapp的單元測試模組test,請先看下目前test下的檔案結構:        目前__init__.py檔案還是空,請檢視test_basic.py的程式碼: import unittest from flask impor

IDEA Maven專案利用Junit4進行單元測試

    最近在開發專案的時候需要寫單元測試,之前一直沒有接觸過,於是從零開始入門學習,查了網上相關資料,總結成為筆記,在此感謝各位大佬的詳細資料!!! 目錄 0、背景 2、實踐 補充: 0、背景     我們在寫好一個函式或者類

利用BouncCheck進行單元測試

今天下載了最新的BoundCheck V10.1試用版進行試用,感覺還是蠻好用的,至少比V6.0.1好用,該版本直接可以嵌入到VC2003及以後版本的Visual stdio中進行單元測試,VC2010也Support, BoundCheck的網站如下,可以下載試試,試用期

利用 Eclipse 進行單元測試

您的傳統程式碼是不是要求使用匹配的類測試套件才能針對其原始碼庫執行?針對此類目的,jMock 堪稱是一個優秀的測試框架。但是,並不是所有情況都能夠適用,尤其是必須以 jMock 不期望的方式構造物件時。為避免生成自定義模擬物件套件才能支援應用程式中的單元測試的麻煩,可以調整

IDEA中利用JUnit進行單元測試

開啟IntelliJ IDEA工具,Alt+Ctrl+S,彈出視窗如下: 在文字框中輸入Plugin進行外掛搜尋設定。 點選按鈕,從外掛資源庫中安裝新的外掛。 從外掛資源庫中搜索JunitGenerator V2.0版本,在外掛位置,滑鼠右擊 選擇Do

Spring學習12-Spring利用mock進行單元測試

一、概述  對於Java元件開發者來說,他們都盼望擁有一組能夠對元件開發提供全面測試功能的好用的單元測試。一直以來,與測試獨立的Java物件相比,測試傳統型J2EE Web元件是一項更為困難的任務,因為Web元件必須執行在某種伺服器平臺上並且它們還要與基於HTTP的Web

SpringBoot介面使用MockMvc進行單元測試

/** * Created by Draven on 2017/11/28. * Email:[email protected] */ @SpringBootTest @RunWith(

利用maven結合Junit4與cobertura進行單元測試

問題說明: 本人利用maven結合Junit與cobertura外掛進行測試時,直接執行如下命令: mvn clean test cobertura:cobertura 結果完全正常(pom檔案中未宣告cobertura外掛的版本、配置等資訊),用例覆蓋率也正

java ssh 框架下 利用junit4 spring-test進行單元測試

ssh框架下  由於bean實列 都交給spring 管理,要做單元測試就比較苦難,junit4 引入註解方便很多; 1. 加入依賴包   使用Spring的測試框架需要加入以下依賴包: Spring Test (Spring框架中的test包)Spring 相關其

利用Spring的mock進行單元測試

1.Spring的mock類 Spring框架提供大量測試用的mock類,包括JNDI相關的mock類,Spring portlet相關的mock類,以及Web應用相關的mock類。尤其是Web應用相關的mock類,可以大大提高Web元件測試的便捷性。以下是Spring所提供的Web應用相關的mock類。

springboot+mockmvc對controlle進行單元測試

依賴 原Controller 建立對應的ControllerTest Spring測試框架提供MockMvc物件,可以在不需要客戶端-服務端請求的情況下進行MVC測試,完全在服務端這邊就可以執行Controller的請求,跟啟動了測試伺服器一樣。 測試開始之前需

NUnit.Framework在VS2015中如何進行單元測試

開放 ron 微軟 strong 擴展 分享 方案 mar 項目 微軟在VS2015中加入了自動化生成測試功能, 在需要測試的源文件的公共方法中右鍵既可以創建單元測試。 不過需要註意的是,要在公共方法中創建,否則會提示這個錯誤 如下是自動化單元測試界面,可以發

利用Mocking Framework 單元測試Entity Framework

dom class exp detached 異步 dbr cnblogs kde num 一、前言   在實際編寫程序時,往往需要與數據庫打交道,在單元測試中直接使用數據庫又顯得太重,如果可以方便的編寫一些測試數據,這樣更易於檢測功能。如何模擬數據庫行為便是本篇的主題。微

在vue-cli生成的項目中使用karma+chrome進行單元測試

使用 設計實現 測試用例 runner 服務 進行 ui界面 包含 node 用vue-cli生成項目時,如果選擇了單元測試,那麽會采用karma+mocha作為單元測試框架,默認使用的瀏覽器是PhantomJs。 Karma是一個基於Node.js的JavaScri

Glib 對 C 函數進行單元測試

error ati 完成 structure 是否 pac str txt b- 1. Glib 單元測試框架 Glib 為單元測試提供了一套完整的測試框架,每個測試運行包括以下幾個部分 測試數據結構 測試 setup 與 teardown 函數 測試函數 2. 單元測

【轉載】IntelliJ IDEA配置JUnit進行單元測試

dbd ima pom.xml format height eight nsh 格式 oot 前提條件 安裝JDK,並配置好環境變量 工程已解決JUnit依賴關系(pom.xml) IDEA中JUnit配置 IDEA自帶一個JUnit插件,打開Settings窗口搜

Spring整合Junit4進行單元測試

CA spa dep pat unit ati 測試 ID sco 一. 添加依賴包(maven) <dependency>   <groupId>junit</groupId>   <artifactId>junit<

IDEA 自動生成Junit進行單元測試

沒有 src ner acc 路徑 name cep csdn ctr 1,從插件資源庫中搜索JunitGenerator V2.0版本,通過此工具自動完成test類的生成。Settings > Plugins 2,配置生成test類的路徑。Settings &