[英]PowerMockito whenNew thenReturn is not working for transitive classes
我有以下情況
Class A {
someMethod() {
B b = new B();
b.someMethod();
}
}
Class B {
String someMethod() {
C c = new C();
return c.someMethod();
}
}
Class C {
String someMethod() {
D d = new D();
return d.getId()
}
}
Class D {
getId() {
return "id123";
}
}
我在我的 UT 做什么
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class, C.class})
MyTest {
public void basicTest() {
D mockDClass = mock(D.class);
when(mockDClass.getId()).thenReturn("mockedId");
PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockClass);
}
}
在我的測試中,它應該返回mockedId
但控制權轉到實際方法。
知道我可能做錯了什么嗎? 當我在我測試的whenNew
中執行新操作時,whenNew 是否有效? 而不是我描述的情況。
----------------------UPDATE---------- 寫了一個簡單的模塊來測試以上
public class A {
public String someMethod() {
B b = new B();
return b.someMethod();
}
}
public class B {
public String someMethod() {
C c = new C();
return c.someMethod();
}
}
public class C {
public String someMethod() {
D d = new D();
return d.getId();
}
}
public class D {
public String getId() {
return "id123";
}
}
測試:
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class, C.class})
public class ATest extends TestCase {
@Test
public void mockTest() {
D mockD = mock(D.class);
when(mockD.getId()).thenReturn("this is from mock");
PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockD);
A a = new A();
System.out.println(a.someMethod());
}
}
這個小測試有效,所以我在實際測試中做錯了。
每次您模擬的 object 實例化時,whenNew 都應該有效。 您實際上應該將 'when(D.getId()).thenReturn("mockedId")' 替換為 'when(mockDClass.getId).thenReturn("mockedId")'。 以下代碼片段應該可以工作:
C 測試:
@RunWith(PowerMockRunner.class)
@PrepareForTest({C.class})
public class CTest {
@Test
public void someMethodTest() throws Exception {
D mockDClass = mock(D.class);
when(mockDClass.getId()).thenReturn("mockedId");
PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockDClass);
C c = new C();
String response = c.someMethod();
verifyNew(D.class).withNoArguments();
assertEquals("mockedId", response);
}
}
測試:
@RunWith(PowerMockRunner.class)
public class DTest {
@Test
public void testId() throws Exception {
D mockDClass = mock(D.class);
when(mockDClass.getId()).thenReturn("mockedId");
PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockDClass);
D d = new D();
verifyNew(D.class).withNoArguments();
String response = d.getId();
assertEquals("mockedId", response);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.