Spring Controller单元测试

SpringMVC controller测试较简单,从功能角度划分,可分为两种。一种是调用请求路径测试,另一种是直接调用Controller方法测试。

调用请求路径测试

通过请求路径调用,请求需要经过拦截器,再到对应的Controller方法处理

被测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/api")
public class MembersController {

    @Autowired
    private MembersService membersService;

    @RequestMapping(value = "/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getUser(HttpServletRequest request, @RequestBody String str,
                         @RequestParam(value = "userId") String userId) {
        Members result = membersService.getMemberById(Integer.valueOf(userId));
        return result.toString();
    }
}

测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)     //调用Spring单元测试类
@WebAppConfiguration        //调用Java Web组件,如自动注入ServletContext Bean等
@ContextConfiguration(locations = {"classpath*:spring-*.xml"})      //加载Spring配置文件
public class MembersControllerTest2 {

    @Autowired
    protected WebApplicationContext wac;

    @Mock
    private MembersService service;

    @InjectMocks
    private MembersController controller;       //需要测试的Controller

    private MockMvc mockMvc;        //SpringMVC提供的Controller测试类

    private String url;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(wac).build();
    }

    @Test
    public void testGetUser() throws Exception {
        url = "the URL to Controller";

        Members m = new Members(3, "wangwu", 1, 5, "12131232342");
        when(service.getMemberById(Mockito.anyInt())).thenReturn(m);

        MvcResult result = mockMvc
                .perform(MockMvcRequestBuilders.post(url)
                        .accept(MediaType.APPLICATION_JSON)
                        .param("userId", "3"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(model().attributeExists("name"))
                .andReturn();
        assertEquals(m.toString(), result.getModelAndView().getModel().get("user").toString());
    }
}

调用Controller方法测试

无法对拦截器和URL路径配置进行测试。测试方法类似于service层单元测试,可以对依赖的service层进行mock。可以参考spring service层单元测试一文

被测试代码示例

测试代码同调用请求路径测试方式部分一样

测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
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.setup.MockMvcBuilders;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)     //调用Spring单元测试类
@WebAppConfiguration        //调用Java Web组件,如自动注入ServletContext Bean等
@ContextConfiguration(locations = {"classpath*:spring-*.xml"})      //加载Spring配置文件
public class MembersControllerTest {
    @Mock
    private MembersService service;

    @InjectMocks
    private MembersController controller;       //需要测试的Controller
    private MockHttpServletRequest request;

    private MockMvc mockMvc;        //SpringMVC提供的Controller测试类

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        request = new MockHttpServletRequest();
    }

    @Test
    public void testGetUser() throws Exception {
        request.addParameter("userId", "100100");

//      request.addParameter("id", "101010");       //如果需要从request取数据,可以在request中添加parameter

        Members m = new Members(3, "wangwu", 1, 5, "12131232342");
        when(service.getMemberById(Mockito.anyInt())).thenReturn(m);

        String response = new String();
        String result = controller.getUser(request, response, "3");
        assertEquals(m.toString(), result);
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏码匠的流水账

聊聊sentinel的NettyHttpCommandCenter

com/alibaba/csp/sentinel/transport/command/NettyHttpCommandCenter.java

921
来自专栏非著名程序员

Retrofit OKHttp 教你怎么持久化管理Cookie

? 投稿作者:黄海杰 原文链接: http://blog.csdn.net/lyhhj/article/details/51345386 绪论 最近小编有点...

36810
来自专栏码匠的流水账

聊聊storm的CheckpointSpout

storm-2.0.0/storm-client/src/jvm/org/apache/storm/topology/TopologyBuilder.java

1176
来自专栏听Allen瞎扯淡

在多线程构建场景下Powermockito无法在不同类中Mock同一个静态方法

在修改单元测试的过程中,不幸踩了个坑,发现 Powermockito 的PowerMock.mockStatic(ClassThatContainsStatic...

1083
来自专栏个人分享

hdfs文件按修改时间下载

应用于:对于不同用户创建的表目录,进行文件的下载,程序中执行hadoop cat命令 下载文件到本地,随后通过ftp传至目标服务器,并将hdfs文件目录的修改时...

1502
来自专栏码匠的流水账

springboot2上报metrics到statsd

micrometer-registry-statsd-1.0.1-sources.jar!/io/micrometer/statsd/StatsdFlavor....

871
来自专栏码匠的流水账

聊聊storm的AssignmentDistributionService

本文主要研究一下storm的AssignmentDistributionService

1191
来自专栏流媒体

App进程启动流程

在上一节Activity的启动流程中,当app进程不存在(第一次启动)时,会先去创建进程。这里我们通过源码来解读app进程的启动流程。

1214
来自专栏个人分享

Hive metastore源码阅读(三)

  上次写了hive metastore的partition的生命周期,但是简略概括了下alter_partition的操作,这里补一下alter_partit...

1092
来自专栏Android干货园

Retrofit+OKHttp 教你怎么持久化管理Cookie

版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/lyhhj/article/details/51...

772

扫码关注云+社区