1. 程式人生 > >springmvc controller junit 測試

springmvc controller junit 測試

servlet dexp type param 建立 問題 spa str params

目錄

  • 1 建立UserController類
  • 2 建立測試類
  • 3 JUnit測試
  • 4 幾個jar包

第一次搭建SSM框架,整合SpringMVC完成後進行Controller測試,找資料並解決問題。

下圖是我的完整目錄:

技術分享圖片

回到頂部

1 建立UserController類

代碼清單 1-1:UserController.java

package org.sei.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.sei.pojo.User;
import org.sei.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController
{
    @Resource
    private UserService userService;
    
    @RequestMapping("/showUser1")
    public String toIndex(HttpServletRequest request,Model model)
    {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        model.addAttribute("user", user);
        return user.getUserName();
    }
    
    @RequestMapping("/showUser3")
    public String toIndex1(User u,Model model)  //註意:參數不同
    {
        int userId = u.getId();
        User user = this.userService.getUserById(userId);
        model.addAttribute("user", user);
        return user.getUserName();
    }
    
}
回到頂部

2 建立測試類

代碼清單 2-1:MockTestController.java

package org.sei.testmybatis;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mybatis.xml","classpath:spring-mvc.xml"})

@WebAppConfiguration
public class  MockTestController
{
   protected MockMvc mockMvc;

   @Autowired
   protected WebApplicationContext wac;

   @Before()  //這個方法在每個方法執行之前都會執行一遍
   public void setup() 
   {
       mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc對象
   }

   @Test
   public void getAllCategoryTest() throws Exception 
   {
       String responseString = mockMvc.perform
           (
               get("/user/showUser1")          //請求的url,請求的方法是get
               //get("/user/showUser2")          //請求的url,請求的方法是get
               .contentType(MediaType.APPLICATION_FORM_URLENCODED)//數據的格式
               .param("id","1")   //添加參數(可以添加多個)
               //.param("id","3")   //添加參數(可以添加多個)
           )
           .andExpect(status().isOk())    //返回的狀態是200
           .andDo(print())         //打印出請求和相應的內容
           .andReturn().getResponse().getContentAsString();   //將相應的數據轉換為字符串
       System.out.println("-----返回的json = " + responseString);
   }

}

回到頂部

3 JUnit測試

  • 測試的數據庫表如下:

技術分享圖片

  • 測試1:參數(HttpServletRequest request,Model model)

技術分享圖片

  • 測試2:參數(User u,Model model)

技術分享圖片

回到頂部

4 幾個jar包

很多問題都來自於確少jar包。

下面給出幾個jar包的Maven依賴:

代碼清單 4-1:pom.xml (局部)

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.3</version>
        </dependency>

來源:https://www.cnblogs.com/oucbl/p/5943743.html

springmvc controller junit 測試