Search code examples
javajunitmockitopowermockito

JUnit for class with static methods with return type as String and void


Below is my class which has static methods.. one with void and another with String as return types.. Using PowerMockito.spy() to doNothing for void method is working.. But for String method it is not working.. Any help/suggestion would be appreciated..

****************************************************************************
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

Solution

  • It works like this for me:

    @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());
        }
    }