JUnit 单元测试-Controller

1.GET请求

1.1 演示接口

@Controller
@RequestMapping(value = "/hello")
public class HelloController {

    @GetMapping("/test")
    @ResponseBody
    public Map<String, String> test() {
        return Collections.singletonMap("message", "Hello");
    }
}

GET请求:http://localhost:8080/hello/test

响应:

{
    "message": "Hello"
}

1.2 测试用例

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

/**
 * @Author : xiao
 * @Date : 17/5/9 下午2:16
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mvc.xml", "classpath:spring/spring-mybatis.xml"})
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否
@Rollback
public class HelloControllerTest {

    private static final Logger logger = LoggerFactory.getLogger(HelloControllerTest.class);

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Before
    public void setUp(){
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testStatus() throws Exception {

        String url = "/hello/test";

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();

    }

    @Test
    public void testMessage() throws Exception {

        String url = "/hello/test";

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(jsonPath("$.message", is("Hello")))
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

    }
}

2. Post请求测试

2.1 请求接口

@PostMapping("/user")
@ResponseBody
public String pstUser(@RequestBody UserVO userVO) {
    logger.info(userVO.toString());
    return CommonResult.success(userVO).toJSON();
}

请求地址:

Post : http://localhost:8080/hello/user

请求参数:

{
    "name": "xiao",
    "age":21,
    "address":"asfasdfasdfasdf.adsfa.asdf"
}

响应:

{
    "data": {
        "address": "asfasdfasdfasdf.adsfa.asdf",
        "age": 21,
        "name": "xiao"
    },
    "message": "成功",
    "status": 1
}

2.2 单元测试

@Test
public void testUser() throws Exception {

    String url = "/hello/user";

    UserVO userVO = new UserVO();
    userVO.setName("xiao");
    userVO.setAge(12);
    userVO.setAddress("asdf.asdfasdf.asdfasd");
    String requestJson = JSONObject.toJSONString(userVO);

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestJson.getBytes())
            .accept(MediaType.APPLICATION_JSON)
    )
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(jsonPath("$.status", is(1)))
            .andExpect(jsonPath("$.message", is("成功")))
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

}

3.常见错误

3.1 EL表达式错误

Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead

pom.xml文件添加依赖:

<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.0</version>
    <scope>test</scope>
</dependency>

3.2 javax.servlet.http.HttpServletRequest 方法找不到

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()

是由于 servlet-api版本引起的:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>test</scope>
</dependency>

3.3 Predicate 类没有找到

java.lang.NoClassDefFoundError: com/jayway/jsonpath/Predicate

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
    <scope>test</scope>
</dependency>

猜你喜欢

转载自blog.csdn.net/jeikerxiao/article/details/79911518