[英]Unable to properly mock method call when called from inside another class method
MyClass firstClass = PowerMockito.spy(new MyClass());
AnotherClass secondClass;
secondClass = PowerMockito.mock(AnotherClass.class);
PowerMockito.when(secondClass.anotherFunction(Mockito.any()).thenReturn(1);
int myInt = firstClass.myFunction();
if (myInt == 1) {
System.out.println("true");
}
myFunction
要求anotherFunction
並返回結果anotherFunction
。
但它並沒有像我期望的那樣返回1
並打印"true
”,而是仍然在做它真正的功能。
我在這里錯過了什么?
在myFunction中創建了AnotherClass的實例,然后該實例用於從myFunction內部調用secondClass.anotherFunction。
對。 這意味着使用了真實實例,而不是模擬。 測試中的方法與依賴項緊密耦合,因為它自己創建了一個真實的實例
public class MyClass {
public int myFunction() {
AnotherClass secondClass = new AnotherClass();
int result = secondClass.anotherFunction(someValue);
//...
return result;
}
}
我怎樣才能使用模擬實例?
你要么重構注入第二個類,要么通過構造函數或方法參數,這是一個干凈的代碼設計,或者你使用powermock來模擬第二類的初始化,在我看來這是一個糟糕的設計。
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class) //<-- you must prepare the class creating the new instance
public class MyClassTest {
@Test
public void test() {
//Arrange
int expected = 1;
//Mock second class
AnotherClass secondClass;
secondClass = PowerMockito.mock(AnotherClass.class);
PowerMockito.when(secondClass.anotherFunction(Mockito.any()).thenReturn(expected);
//mocking initialization of second class withing first class
PowerMockito.whenNew(AnotherClass.class).withNoArguments().thenReturn(secondClass);
MyClass firstClass = new MyClass();
//Act
int actual = firstClass.myFunction();
//Assert
assertEquals(expected, actual);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.