3

I need to mock a static method only in one test case and wants it to return the original value in all the other testcases.

Class ClassWithStaticMethod
{
    public static boolean aStaticMethod(String param)
    {
       //Some Code;
       return value;
    }
}

/// Test Class
@RunWith(PowerMockRunner.class)
Class ClassWithStaticMethodTest
{
  @Test
  testWhenNotMocked()
  {

     assertTrue(ClassWithStaticMethod.aStaticMethod("str1"));
  }

  @PrepareForTest({ClassWithStaticMethod.class})
  @Test
  testWhenMocked()
  {
     PowerMockito.mockStatic(ClassWithStaticMethod.class);
     when(ClassWithStaticMethod.aStaticMethod("str1")).thenReturn(false);
     assertFalse(ClassWithStaticMethod.aStaticMethod("str1"));
  }
}

But the code is always returning false.

  • 1
    According to the `@PrepareForTest` javadoc if it is placed at test method it modifies target class for this method only. So your code should work. Try to replace `return value;` to `return true;` in `aStaticMethod` and see what will happen. – Evgeny Apr 22 '16 at 09:39

0 Answers0