天天看點

Mockito單元測試架構學習

一、問題:如何将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/