0

If there is a method of a class like:

public String createA(String message) {
    . . .

    String sec = MDI.check(message, ..., ...);
    if sec == null throw . . . 

    return something;
}

What is the way to test createA(message) and mock, stub, ... the call to MDI. I mean, I want to check in the test that the call in createA to MDI.check(...) returns something I want.

@Test
public void testcreateA() {

}
John Fadria
  • 1,863
  • 2
  • 25
  • 31
  • 2
    https://code.google.com/p/powermock/wiki/MockStatic – Kelvin Ng Oct 16 '14 at 07:43
  • 2
    Ideally you would try to avoid the static call - can you make the method non static and inject an MDI instance into your class? A good read: [Google guide on Writing Testable Code](http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf). – assylias Oct 16 '14 at 07:49
  • Hi @assylias, non static yes, put inject no, createA is a REST GET operation. – John Fadria Oct 16 '14 at 08:49

1 Answers1

0

In your case, you can use PowerMock framework to mock the static call MDI.check(message, ..., ...) and then test your method.

Test class would be something like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MDI.class)
public class FooTest {

   @Test
   public void testCreateA() throws Exception {
      PowerMockito.mockStatic(MDI.class);
      PowerMockito.when(MDI.check(anyString(), anyString(), anyString())).thenReturn("Expected Answer");
      // test createA method
   }
}

Note you need to run the test with PowerMockRunner. There are a lot of examples in PowerMock documentation and some stackoverflow questions talking about it (example)

Hope it helps.

Community
  • 1
  • 1
troig
  • 7,072
  • 4
  • 37
  • 63
  • Hi @troig, With PowerMock is possible to mock static objects, but I can not see in any examples how to mock the call inside the class tested :( – John Fadria Oct 16 '14 at 14:30
  • I'm not sure if I'm undertand you correctly... but I think my answer example is precisely doing this: `PowerMockito.when(MDI.check(anyString(), anyString(), anyString())).thenReturn("Expected Answer");` I'm wrong? – troig Oct 16 '14 at 14:36
  • Yes @troig, Sorry, I get it. Thanks!!!. Now I have problems between PowerMock and rest-assured http://stackoverflow.com/questions/26401642/using-powermock-to-mock-static-class-in-a-rest-assured-test :( – John Fadria Oct 16 '14 at 15:36