一、问题:如何将mock的类自动注入到待测类,特别是在没有setter方法的情况下。
解答:
前提:待测的service类及其依赖的其他类都是处在被spring管理中的。
就可以使用mockitoannotations.initmocks(this);这句话自动将依赖的类注入待测类,如果依赖类在spring的管理下有自己的name,那么甚至在待测类中都不需要写setter方法。
例:
1、待测类
@component("abcservice")
public class abcservice {
@resource(name="aaadao")
private aaadao aaadao;
@resource(name="bbbdao")
private bbbdao bbbdao;
......//注:此处省略的代码中并不包含aaadao和bbbdao的setter方法。
}
2、测试类
public class abcservicetest{
@injectmocks
abcservice abcservice;
@mock
aaadao aaadao;
bbbdao bbbdao;
@before
public void setup(){
mockitoannotations.initmocks(this);//这句话执行以后,aaadao和bbbdao自动注入到abcservice中。
//在这之后,你就可以放心大胆地使用when().then()等进行更详细的设置。
二、问题:如何对连续的调用进行不同的返回
对连续的调用进行不同的返回 (iterator-style stubbing)
还记得在实例2中说道当我们连续两次为同一个方法使用stub的时候,他只会使用最新的一次。但是在某一个方法中我们确实有很多的调用怎么办呢?mockito当然想到这一点了:
when(mock.somemethod("some arg"))
.thenthrow(new runtimeexception())
.thenreturn("foo");
//first call: throws runtime exception:
mock.somemethod("some arg");
//second call: prints "foo"
system.out.println(mock.somemethod("some arg"));
//any consecutive call: prints "foo" as well (last stubbing wins).
当然我们也可以将第一句写的更简单一些:
when(mock.somemethod("some arg"))
.thenreturn("one", "two", "three");
最新内容请见作者的github页:http://qaseven.github.io/