欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java单测void类型的方法详解

程序员文章站 2024-03-08 13:11:22
前言 我们在学java的时候,老师或者一般的书上都写着,java的基本类型有八种。分别是:byte、int、short、long、float、double、char、bo...

前言

我们在学java的时候,老师或者一般的书上都写着,java的基本类型有八种。分别是:byte、int、short、long、float、double、char、boolean。但是,今早我在看java的圣经——《thinking in java》的时候,发现作者在说明数据类型的时候,把void也放上去了。这样就有九种了。百度了一下,有些书也是写的java有九种基本类型。

java的sevice层会有很多void类型的方法,比如save*、update*,这类方法只是做一些更新,不会有返回值,其单测不能根据方法的返回值来编写,只能采用特殊方法;

本方法环境:mockito、testng

被测试的方法:

想要被测试的void方法java

@override
 public void updaterulename(long ruleid, string newrulename, long ucid) {
 assert.notnull(ruleid, "规则id不能为null");
 assert.notnull(newrulename, "规则名称不能为null");
 assert.notnull(ucid, "操作人的ucid不能为null");
 
 string cleannewrulename = stringutils.trim(newrulename);
 if (stringutils.isblank(cleannewrulename)) {
  throw new illegalargumentexception("新的规则名称不能为空");
 }
 
 // 查询规则对象
 rule rule = queryrulebyid(ruleid);
 if (null == rule) {
  throw new illegaldataexception("没有查到该规则");
 }
 
 rule.setruleid(ruleid);
 rule.setrulename(cleannewrulename);
 rule.setupdateucid(ucid);
 rule.setupdatetime(new date());
 
 ruledao.updateselective(rule);
 }

测试的方法:

void返回的方法测试java

 @test
 public void testupdaterulename() {
 long ruleid = 1l;
 string newrulename = "newrulename";
 long ucid = 123l;
 
 list<rule> rules = new arraylist<rule>();
 rule rule = new rule();
 rule.setrulestatus((byte) dbvaluesetting.rule_status_take_effect);
 rules.add(rule);
 
 // 查询规则对象
 map<string, object> params = new hashmap<string, object>();
 params.put("ruleid", ruleid);
 mockito.when(ruledao.queryrulesbycondition(params)).thenreturn(rules);
 
 mockito.doanswer(new answer<object>() {
  public object answer(invocationonmock invocation) {
  // 断点2:这里随后执行
  rule rule = (rule) invocation.getarguments()[0];
  assert.asserttrue(rule.getrulename().equals("newrulename"));
  return null;
  }
 }).when(ruledao).updateselective(mockito.any(rule.class));
 
 // 断点1:先执行到这里
 ruleservice.updaterulename(ruleid, newrulename, ucid);
 }

如注释所示,如果加了两个断点的话,执行的过程中,会先执行最后的调用行,端点1执行的过程中,会执行到端点2的stub,这时候在断点2可以获取到方法执行的入参,对入参进行assert校验,即可实现目的;

new anwer是个接口,其中只有一个方法,用于设置方法调用的代理执行入口

doanswer的实现java

public interface answer<t> {
 /**
 * @param invocation the invocation on the mock.
 *
 * @return the value to be returned
 *
 * @throws throwable the throwable to be thrown
 */
 t answer(invocationonmock invocation) throws throwable;
}

当代码执行到“ ruledao.updateselective(rule); ”的时候,会触发针对mock对象调用的拦截器,在拦截器中,会创建一个动态代理,动态代理的invocation就是new answer中覆盖的方法;

使用拦截、代理两种方法,实现了对mock对象方法的入参、出参的设定和获取,使用这种方式,就可以校验void方法内部的执行类调用的情况;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。