spring boot学习系列:spring boot的单元测试实战

spring boot学习系列:spring boot的单元测试实战

    前面介绍了两篇关于springboot的博客,一篇是入门篇:点击打开链接,另一篇是与 jdbcTemplate的整合开发:点击打开链接。对于springboot的发展以及应用,近来鄙人也在进一步学习中,后续将会陆续进入微服务架构实战,博客也将会逐步更新,当然啦,偶尔会插入服务中间件的介绍与实战、第三方接口开发实战的介绍等等。

    这篇博客主要是从springboot再次给开个头,继续学习微服务架构方面的知识。以前就已经介绍过了,开发好controller层之后就可以通过postman进行模拟。今天要介绍一个简单的用于junit单元测试的mock模拟工具。

    搭建的过程我就不重复了,有需要的可以参考前面两篇博客。

    下面是写好的controller:

package com.steadyjack.springboot.controller;

import com.steadyjack.springboot.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by zhonglinsen on 2017/8/14.
 */
@Controller
public class UserController {

    private static final String prex="user";

    private static final Logger log= LoggerFactory.getLogger(UserController.class);

    /**
     * get请求无参数
     * @return
     * @throws Exception
     */
    @RequestMapping(value = prex+"/getUserDto",method = RequestMethod.GET)
    @ResponseBody
    public UserDto getUserDto() throws Exception{
        UserDto userDto=new UserDto();
        userDto.setUserName("steadyjack-debug");
        userDto.setSex("man");
        userDto.setAddress("北京丰台车公庙区域");

        return userDto;
    }

    /**
     * get请求带参数
     * @param name
     * @return
     * @throws Exception
     */
    @RequestMapping(value = prex+"/getUserDtoByName",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public UserDto getUserDtoByName(String name) throws Exception{
        log.debug("请求参数: {}",name);

        UserDto userDto=new UserDto();
        userDto.setUserName(name);
        userDto.setSex("man");
        userDto.setAddress("北京丰台车公庙区域-"+name);

        return userDto;
    }

    /**
     * post请求-application/json的格式 - 其他的也是一个道理
     * @param userDto
     * @return
     * @throws Exception
     */
    @RequestMapping(value = prex+"/saveUserDto",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public UserDto saveUserDto(@RequestBody UserDto userDto) throws Exception{
        log.debug("post请求插入参数: {}",userDto);

        return userDto;
    }
}

    上面的@Controller以及@ResponseBody其实也可以完全用@RestController来代替,这里就不赘诉了。

     下面是junit单元测试类(放在src/test/java下)

package com.steadyjack.springboot;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.steadyjack.springboot.controller.UserController;
import com.steadyjack.springboot.dto.UserDto;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootApplication
@WebAppConfiguration
public class SpringbootP1ApplicationTests {

	private static final Logger log= LoggerFactory.getLogger(SpringbootP1ApplicationTests.class);

	private MockMvc mvc;

	@Before
	public void setUp() throws Exception{
		mvc= MockMvcBuilders.standaloneSetup(new UserController()).build();
	}

	@Test
	public void test1() throws Exception{
		log.debug("测试get请求无参数......");

		//mock进行模拟
		mvc.perform(MockMvcRequestBuilders.get("/user/getUserDto").accept(MediaType.APPLICATION_JSON))
				.andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(MockMvcResultHandlers.print())
				.andReturn();
	}

	@Test
	public void test2() throws Exception{
		log.debug("测试get请求带参数......");

		String myName="debug-steadyjack-大圣";
		//mock进行模拟
		mvc.perform(MockMvcRequestBuilders.get("/user/getUserDtoByName").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).param("name",myName))
				.andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(MockMvcResultHandlers.print())
				.andReturn();
	}


	@Test
	public void test3() throws Exception{
		log.debug("测试post请求带参数......");

		UserDto userDto=new UserDto();
		userDto.setUserName("debug--大圣");
		userDto.setAddress("北京大同");
		userDto.setSex("男的");
		log.debug("post 参数: {}",userDto);

		ObjectMapper objectMapper=new ObjectMapper();
		String requestJson=objectMapper.writeValueAsString(userDto);

		//mock进行模拟
		mvc.perform(MockMvcRequestBuilders.post("/user/saveUserDto").accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
				.content(requestJson))
				.andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(MockMvcResultHandlers.print())
				.andReturn();
	}
}

    跑第一个test1,会得到如下的效果,http的请求头、请求体与请求行  跟 响应头、响应体与状态行 一览无遗:



    跑第二test2(),效果如下:



   最后一个test3()的效果:



   好了,就介绍到这里了,如果有需要交流的地方,可以加入群:java开源技术群:583522159 我叫debug

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修罗debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值