[英]How to test that method was called inside another method
我有一些丑陋的課要測試,然后我不得不承認我不能修改它。 因此,讓我們看一下問題的根源。
我有一類,有一個相當長的靜態方法,如下所示:
public class SomeClass{
public SomeClass(){
}
public static String Dispatch(HttpServletRequest request){
String param1= request.getParameter("param1");
String param2 = request.getParameter("param2");
Factory factory = // .. some Bean, used as Factory
// lot, lot if.. else statements that returning smth based on params
if(param1.equalsIgnoreCase("smthParam1")){
if(param2.equalsIgnoreCase("smthParam2")){
factory.getInstance().invokeSmth();
} else if(param2.equalsIgnoreCase("smthParam2_2")){
factory.getAnotherObjectInstance().invokeSmth();
} else if(param2.equalsIgnoreCase("smthParam2_3")){
factory.getYetAnotherObjectInstance().invokeSmth();
}
}
// More if.. else statements...
return "Error";
}
}
然后,我想測試一下,如果有一些請求參數,它將從工廠調用Singleton方法。
我不知道該怎么做,有可能嗎? 請記住,我無法更改原始代碼。 感謝幫助。
PowerMock也許可以為您提供幫助。 據我了解, MockConstructor應該可以解決問題。 遵循鏈接文檔中的示例,您應該得到如下內容:
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeClass.class)
public class SomeClassTest {
@Test
public void testCreateDirectoryStructure_ok() throws Exception {
// create parameters for factory creation
Factory factoryMock = createMock(Factory.class);
SomeClass tested = new SomeClass();
expectNew(Factory.class, /* parameters */).andReturn(factoryMock);
// mock factory methods
replay(factoryMock, Factory.class);
tested.Dispatch(/*...*/);
// assert / verify interaction
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.