1

Is there a way to mock a static method with a parameter.

I have seen many questions regarding this question, but I am not able to find any related to it.

Example : Helper.class has a static method called getName(String abc);

I want to mock method getName, the same way I can mock a normal method.

I tried using PowerMockito but it didnt work.

Edit: I m getting MissingmrthodInvocationException : when() requires an argument wjich has to be 'a method call on a mock'

Its resolved by declaring PowerMockito.when().thenReturn() using @Before in setup block

javaAndBeyond
  • 520
  • 1
  • 9
  • 26
  • _How_ did using PowerMock not work? – Mick Mnemonic Jul 21 '16 at 00:57
  • thanks, but i m getting MissingmrthodInvocationException : when() requires an argument wjich has to be 'a method call on a mock' – javaAndBeyond Jul 21 '16 at 02:14
  • Hint: please turn to the help center and learn how to ask "code aint working" questions. We can't tell you if you don't show us your code. – GhostCat Jul 21 '16 at 07:14
  • Side note: you should not mock static method calls. Because: you should not be using static method calls in code that you want to test. Meaning: using **static** is an abnormality to good OO design; so you avoid it where possible. Then you are also not forced to turn to PowerMock (which is often causing more problems than it solves). Long story short: you might want to watch https://www.youtube.com/playlist?list=PLD0011D00849E1B79 ... – GhostCat Jul 21 '16 at 07:16
  • I'm using the same code given in below answer. I'm using testng – javaAndBeyond Jul 21 '16 at 07:21

1 Answers1

0

You can mock static methods using PowerMockito. Here is a complete example.

@RunWith(PowerMockRunner.class)
@PrepareForTest(Helper.class)
public class YourTestCase {
   @Test
   public void testMethodThatCallsStaticMethod() {
      // mock all the static methods in a class called "Static"
      PowerMockito.mockStatic(Helper.class);
      // use Mockito to set up your expectation
      Mockito.when(Helper.getName("abc")).thenReturn("foo");

      // execute your test
      String result = Helper.getName("abc");

      //assert the result
      Assert.assertEquals("foo", result);

      // to start verifying behavior
      PowerMockito.verifyStatic(Mockito.times(1));
      // IMPORTANT:  Call the static method you want to verify
      Helper.getName("abc");
  }
}
Rodrigo Villalba Zayas
  • 5,326
  • 2
  • 23
  • 36