I've got some ugly class to test, then i have to admit that I can't modify it. So let's go to base of the problem.
I've got a class, with one pretty long static method, like this:
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";
}
}
Then, I want to test that, if there is some request params it will invoke a Singleton method from factory.
I have no idea how to do that, Is it possible to do? Please remember that I can't change the original code. Thank's for help.
PowerMock may be able to help you. As I understand it the MockConstructor should do the trick. Following the example from the linked documentation, you should get something like this:
@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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.