class 的 JUnit,具有 return 类型为 String 和 void 的静态方法
JUnit for class with static methods with return type as String and void
下面是我的 class,它有静态方法。一个是 void,另一个是 String 作为 return 类型。使用 PowerMockito.spy() doNothing for void 方法是有效的..但是对于 String 方法它不起作用..任何 help/suggestion 将不胜感激..
****************************************************************************
public class ServiceImpl {
public static String getName(){
// some business logic
Utils.doSomething();
String result = Utils.getName();
return result;
}
}
****************************************************************************
public class Utils {
public static void doSomething(){
// some DB business logic
}
public static String getName(){
// some business logic
return "Static String";
}
}
****************************************************************************
PowerMockito.spy(Utils.class);
PowerMockito.doNothing().when(Utils.class); // working
PowerMockito.when(Utils.getName()).thenReturn("TESTER"); // not working
对我来说是这样的:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class SimpleTest {
@Test
public void test() throws Exception {
PowerMockito.spy(Utils.class);
PowerMockito.doNothing().when(Utils.class, "doSomething"); // add method name
PowerMockito.when(Utils.getName()).thenReturn("TESTER");
assertEquals("TESTER", ServiceImpl.getName());
}
}
下面是我的 class,它有静态方法。一个是 void,另一个是 String 作为 return 类型。使用 PowerMockito.spy() doNothing for void 方法是有效的..但是对于 String 方法它不起作用..任何 help/suggestion 将不胜感激..
****************************************************************************
public class ServiceImpl {
public static String getName(){
// some business logic
Utils.doSomething();
String result = Utils.getName();
return result;
}
}
****************************************************************************
public class Utils {
public static void doSomething(){
// some DB business logic
}
public static String getName(){
// some business logic
return "Static String";
}
}
****************************************************************************
PowerMockito.spy(Utils.class);
PowerMockito.doNothing().when(Utils.class); // working
PowerMockito.when(Utils.getName()).thenReturn("TESTER"); // not working
对我来说是这样的:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class SimpleTest {
@Test
public void test() throws Exception {
PowerMockito.spy(Utils.class);
PowerMockito.doNothing().when(Utils.class, "doSomething"); // add method name
PowerMockito.when(Utils.getName()).thenReturn("TESTER");
assertEquals("TESTER", ServiceImpl.getName());
}
}