controller 测试 不使用其他api接口测试工具

一般而言,我们写好一个模块后,会对其进行单元测试,再集成到现有的系统中。

但是呢~针对Controller、Service、Dao三层来说,我们最常的是对Service和Dao进行单元测试。然而Controller的测试,很多人还是启动Tomcat,使用Postman进行api测试,这样不仅需要等待很长的编译部署时间,而且无法逐个Controller功能进行单独测试,因此特意总结Controller层的单元测试。顺便说下,Postman挺好用的,只是我们仍然需要启动tomcat,有点浪费时间。

那么,我们需要有一种不需启动tomcat就可以测试controller层的方法。

接下来我们细细讲来。

controller所采用的是SpringMVC框架 。SpringMVC已经继承了单元测试的类

步骤:

1.创建普通类文件

2.引入Spring单元测试注释

@RunWith(SpringJUnit4ClassRunner.class) // 此处调用Spring单元测试类
@WebAppConfiguration // 调用javaWEB的组件,比如自动注入ServletContext Bean等等
@ContextConfiguration(locations = { "classpath:context.xml", "classpath:mvccontext.xml" }) // 加载Spring配置文件
public class TestPayTypeController {
@Autowired
PayTypeController payTypeController;//测试的controller类 @Autowired
ServletContext context; MockMvc mockMvc; @Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(payTypeController).build();
}
}

注意:

@WebAppConfiguration如果不加的话,是没法调用WEB的一些特性的。经常会被遗忘掉。。。

@ContextConfiguration中,需要把所有Spring的配置文件全部加载进来,因为有的项目中Spring 的xml配置是分拆的。 此处的xml是放在resources的根目录中。

3.引入spring注解后,Controller的单元测试需要模拟Server的运行,需要在class中进行WEB环境的初始化。

MockMvc是SpringMVC提供的Controller测试类

每次进行单元测试时,都是预先执行@Before中的setup方法,初始化PayTypeController单元测试环境。

4.前期准备工作都做好了。可以编写单元测试方法了。

先看get方法请求

ResultAction是用来模拟Browser发送FORM表单请求的。get()是请求的地址,accept()请求的内容 ;

@org.junit.Test // get请求
public void getListTest() throws Exception {
// 发送请求
ResultActions resultActions = this.mockMvc
.perform(MockMvcRequestBuilders.get("/paytype/list/all").accept(MediaType.APPLICATION_JSON));
MvcResult mvcResult = resultActions.andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("客户端获的数据:" + result);
}

在控制台打印如下,说明成功了!

接下来使用post 请求;

ResultAction是用来模拟Browser发送FORM表单请求的。post()是请求的地址,accept()请求的内容 param()请求的键值对,如果有多个参数可以后缀调用多个param();

MvcResult是获得服务器的Response内容。

@org.junit.Test // post请求
public void addTest() throws Exception {
// 发送请求
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/paytype/add")
.accept(MediaType.APPLICATION_JSON).param("typename", "一年停").param("payfee","4444.0").param("payto", "post"));
MvcResult mvcResult = resultActions.andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("客户端获的数据:" + result);
}

成功插入数据库;

一般常用的就get,post请求;至此,我们不需启动tomcat就能测试controller层的method。

附上controller类的method

    @RequestMapping(value = "/add", method = RequestMethod.POST)
public ResultMessage add(PayTypeModel ptm) throws Exception {
ResultMessage result = new ResultMessage();
payTypeService.add(ptm);
result.setResult("Y");
result.setMessage("增加缴费类型成功");
return result; } @RequestMapping(value="/get",method=RequestMethod.GET)
public PayTypeModel get(@RequestParam int typeno) throws Exception
{
return payTypeService.get(typeno);
}

如有错误,欢迎留言指正!

controller 单元测试的更多相关文章

  1. Spring MVC Controller 单元测试

    简介 Controller层的单元测试可以使得应用的可靠性得到提升,虽然这使得开发的时间有所增加,有得必失,这里我认为得到的比失去的多很多. Sping MVC3.2版本之后的单元测试方法有所变化,随 ...

  2. Spring Controller单元测试

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

  3. Spring Boot Controller单元测试

    一.创建Controller 一个方法是用传统IO来下载文件,一个是NIO下载文件 @Controller public class FileController { private Logger l ...

  4. Mvc Controller 单元测试 Mock User.Identity.Name

    被测试的Action 包含 User.Identity.Name 代码,在写测试代码需要Mock ControllerContext对象 代码如下: var mock = new Mock<Co ...

  5. Mvc controller单元测试 Mock Url对象

    被测试Action 包含有Url对象的代码: data = new data { title = ds.Name, icon = "folder", attr = new { id ...

  6. Spring Boot从Controller层进行单元测试

    单元测试是程序员对代码的自测,一般公司都会严格要求单元测试,这是对自己代码的负责,也是对代码的敬畏. 一般单元测试都是测试Service层,下面我将演示从Controller层进行单元测试. 无参Co ...

  7. SpringBoot系列: 单元测试

    SpringBoot 项目单元测试也很方便, Web项目中单元测试应该覆盖:1. Service 层2. Controller 层 本文前半部分讲解是一些测试基础配置. 对于Service和Contr ...

  8. spring boot快速入门 9: 单元测试

    进行单元测试: service第一种方式: 第一步:在指定service中创建一个方法进行测试 /** * 通过ID查询一个女生的信息 * @param id * @return */ public ...

  9. spring-boot单元测试

    一.为什么要写单元测试 很多程序员有两件事情不愿意做: 写注释. 写单元测试. 但是在看代码时又会希望有清晰明了的注释,重构代码时能有一套随时可以跑起来的单元测试. 最近在迁移一个项目,从sqlser ...

随机推荐

  1. [国嵌攻略][097][U-Boot新手入门]

    嵌入式软件层次 1.Bootloader 2.Linux内核 3.文件系统 编译U-Boot 1.解压uboot tar zxvf uboot.tar.gz 2.清除uboot make distcl ...

  2. [国嵌攻略][072][Linux应用程序地址布局]

    程序构成 代码段.数据段.BSS段(Block Started by Symbol,又叫:未初始化数据段).堆(heap)和栈(stack).这些部分构成了Linux应用程序的重要组成部分. 内存布局 ...

  3. Oracle_事务

    Oracle_事务 -事物管理   create table account(        id number,        money number );     --实现转账操作 update ...

  4. Linq 实例

    1.分页 ).Take(); 2.分组 1)一般分组 //根据顾客的国家分组,查询顾客数大于5的国家名和顾客数var 一般分组 = from c in ctx.Customers group c by ...

  5. Redis单机版安装

    1.工具简单介绍 1.博主使用的是Xshell工具 ps:需要设置端口和连接名称,端口一般默认为22,需要的童鞋可以自行百度 2.Redis单机版安装 第一步:安装gcc编译环境 yum instal ...

  6. IOS学习:隐藏键盘方法

    1.点击界面的其它空白地方隐藏      由于UIViewController是继承自UIResponder的,所以可以覆写- (void)touchesBegan:(NSSet *)touches ...

  7. [ios 开发笔记]:一句话笔记

    1.NSString转int int a=[@"123" intValue]; 同样适用于NSDictionary将NSNumber转为int   2.switch(stateme ...

  8. 微信小程序+和风天气完成天气预报

    <冷暖自知>天气小程序 学无止境,以玩儿玩儿的心态去学习! 花半天时间完成简单的小程序应用.适合小程序初学者. 申请小程序帐号: https://mp.weixin.qq.com/wxop ...

  9. 使用WinDbg获取SSDT函数表对应的索引再计算得出地址

    当从Ring3进入Ring0的时候会将所需要的SSDT索引放入到寄存器EAX中去,所以我们这里通过EAX的内容得到函数在SSDT中的索引号,然后计算出它的地址首先打开WinDbug,我们以函数ZwQu ...

  10. Oracle实战笔记(第六天)之PL/SQL基础

    一.PL/SQL介绍 1.概念 PL/SQL也是一种程序语言,叫做过程化SQL语言(Procedural Language/SQL).PL/SQL是Oracle数据库对SQL语句的扩展.在普通SQL语 ...