時間 2015-06-16 21:15:05 BlogJava-技術區html
原文 http://www.blogjava.net/usherlight/archive/2015/06/16/425740.htmljava
主題 Java函數
本文將簡單介紹如何使用PowerMock和Mockito來mock單元測試
1. 構造函數測試
2. 靜態函數ui
3. 枚舉實現的單例this
4. 選擇參數值作爲函數的返回值spa
一點簡要說明:Mockito其實已經能夠知足大部分的需求,可是它的實現機制是使用cglib來動態建立接口的類的實例。可是這種實現方式不能用於構造函數和靜態函數,由於那須要使用類的字節碼(好比使用javassist). 因此咱們才須要結合使用PowerMock..net
1. mock構造函數, 若是有代碼沒有使用DI注入依賴實例,在單元測試中能夠使用PowerMock來模擬建立對象。code
注意的開始兩行的2個註解 @RunWith 和 @PrepareForTest
@RunWith比較簡單,後面始終是PowerMockRunner.class
@PrepareForText後面須要加的是調用構造函數的類名,而不是有構造函數的類自己。
在下面的例子中,咱們要測試的類是:Helper, 在Helper類中調用了Somthing類的構造函數來建立實例。
@RunWith(PowerMockRunner. class
)
@PrepareForTest(Helper.
class
)
public class
HelperTest {
@Mock
private
Something mockSomething;
@InjectMocks
private
Helper helper;
@Test
public void doSomething() throws
Exception {
String argument
= " arg "
;
PowerMockito.whenNew(Something.
class
).withArguments(argument).thenReturn(mockSomething);
// 調用須要測試方法
helper.doSomething(argument);
// 進行驗證
verify(mockSomething).doIt();
}
}
public class Helper {
public void doSomething(String arg) {
Something something = new Something(arg);
something.doit();
}
}
2,mock 靜態函數, 單例模式就是一個典型的會調用靜態函數的例子。 注意要點與mock構造函數相同。
class
ClassWithStatics {
public static
String getString() {
return " String "
;
}
public static int
getInt() {
return 1
;
}
}
@RunWith(PowerMockRunner.
class
)
@PrepareForTest(ClassWithStatics.
class
)
public class
StubJustOneStatic {
@Test
public void
test() {
PowerMockito.mockStatic(ClassWithStatics.
class
);
when(ClassWithStatics.getString()).thenReturn(
" Hello! "
);
System.out.println(
" String: " +
ClassWithStatics.getString());
System.out.println(
" Int: " +
ClassWithStatics.getInt());
}
}
3。mock枚舉實現的單例
SingletonObject.java
public enum SingletonObject { INSTANCE; private int num; protected void setNum(int num) { this.num = num; } public int getNum() { return num; } }
SingletonConsumer.java
public class SingletonConsumer {
public String consumeSingletonObject() { return String.valueOf(SingletonObject.INSTANCE.getNum()); } }
SingletonConsumerTest.java
@RunWith(PowerMockRunner.class) @PrepareForTest({SingletonObject.class}) public class SingletonConsumerTest { @Test public void testConsumeSingletonObject() throws Exception { SingletonObject mockInstance = mock(SingletonObject.class); Whitebox.setInternalState(SingletonObject.class, "INSTANCE", mockInstance); when(mockInstance.getNum()).thenReturn(42); assertEquals("42", new SingletonConsumer().consumeSingletonObject()); } }
4。返回參數值作爲函數返回值。
mockito 1.9.5以後,提供一個方便的方法來實現這個須要,在這以前能夠使用一個匿名函數來返回一個answer來實現。
when(myMock.myFunction(anyString())).then(returnsFirstArg());
其中returnsFirstArg()是org.mockito.AdditionalAnswers中的一個靜態方法。
在這個類中還有其餘的一些相似方法
returnsSecondArg()
returnsLastArg()
ReturnsArgumentAt(int position)