[英]Mocking a local object inside a method of SUT using Mockito or PowerMocktio
我有下面的類方法,它創建一個本地對象並在該本地對象上調用一個方法。
public class MyClass {
public someReturn myMethod(){
MyOtherClass otherClassObject = new MyOtherClass();
boolean retBool = otherClassObject.otherClassMethod();
if(retBool){
// do something
}
}
}
public class MyClassTest {
@Test
public testMyMethod(){
MyClass myClassObj = new MyClass();
myClassObj.myMethod();
// please get me here..
}
}
在測試myMethod
,我想模擬otherClassObject.otherClassMethod
以返回我選擇的內容。 otherClassMethod對消息隊列做了一些類,而我在單元測試中不希望這樣。 所以我想在執行otherClassObj.otherClassMethod()時返回true。 我知道在這種情況下,我必須為MyOtherClass
實例化使用了工廠,但這是舊代碼,我現在不想更改任何代碼。 我看到在這種情況下Mockito沒有提供模擬MyOtherClass
,但是PowerMockito可以提供這種功能。 但是,我找不到上述情況的示例,而只為靜態類找到了。 我應該如何在SUT方法中模擬本地對象?
我還提到了其他一些OS問題,例如- 用Mockito模擬本地作用域對象的方法,但它們沒有幫助。
一個代碼示例將有很大的幫助。
如果您使用的是PowerMockito,則可以使用whenNew
方法
它看起來應該像這樣:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class) //tells powerMock we will modify MyClass to intercept calls to new somewhere inside it
public class MyClassTest{
@Test
public void test(){
MyOtherClass myMock = createMock(MyOtherClass.class);
//this will intercept calls to "new MyOtherClass()" in MyClass
whenNew( MyOtherClass.class).withNoArguments().thenReturn( myMock) );
... rest of test goes here
}
另外這則SO帖子也有示例代碼PowerMockito在新時不起作用模擬
好的,這不是一個真正的答案,但是使用PowerMockito,您可以執行以下操作:
final MyOtherClass myOtherClass = mock(MyOtherClass.class);
// mock the results of myOtherClass.otherClassMethod();
PowerMockito.whenNew(MyOtherClass.class).withNoArguments()
.thenReturn(myOtherClass);
// continue with your mock here
現在,不知道你是否真的需要這樣的結果otherClassMethod在這里,但如果你不這樣做,我建議你嘲笑的結果myMethod()
代替-除非myMethod()
是要測試,因為這等什么方法對它有影響,是的,在這種情況下,應考慮重構...而不是延遲確定時間...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.