How to use Mockito correctly on static methods wrapped inside non-static methods?

so I am trying to use Mockito for a method that has a static method. The reason is that I cannot use PowerMock, so I wrapped the method under a non-static method.

public class WrapperUtil {

    public String getURLContent(String path) throws IOException{
        URL url = new URL(path);
        return IOUtils.toString(url);
    }
}

      

I have now tested the WrapperUtil class in two different ways. One test worked but did not provide any coverage for the WrapperUtil class, another throws a null pointer exception associated with a static method.

This is the one that works but has not provided any coverage.

@RunWith(MockitoJUnitRunner.class)
public class WrapperUtilTest {

    @InjectMocks
    WrapperUtil ioutils;


    @Before
    public void setUp() throws Exception {

        ioutils = new WrapperUtil();
    }

    @Test
    public void testGetUrlContent() throws IOException {

        WrapperUtil ioutilsSpy = Mockito.spy(ioutils);
        Mockito.doReturn("test").when(ioutilsSpy).getURLContent(Mockito.anyString());
        assertTrue(ioutils2.getURLContent("test").contains("test"));

    }

}

      

This is the one that doesn't work:

@RunWith(MockitoJUnitRunner.class)
public class WrapperUtilTest {

    @InjectMocks
    WrapperUtil ioutils;


    @Before
    public void setUp() throws Exception {

        ioutils = new WrapperUtil();
    }

    @Test
    public void testGetUrlContent() throws IOException {

        WrapperUtil ioutilsSpy = Mockito.spy(ioutils);
        Mockito.when(ioutilsSpy).getURLContent(Mockito.anyString()).thenReturn("test");
        assertTrue(ioutils2.getURLContent("test").contains("test"));

    }

}

      

How can I make this work and get code coverage without using PowerMockito? Thank you so much for your help.

+3


source to share


1 answer


My two cents:

  • I would go one step further and define an interface to denote functionality
  • On the other hand, I would not go overboard testing the implementation of the shell

Point: there is just a tiny bit of glue . If you can check this code to see if it works, then you are fine.

In other words: Avoid hanging 100% coverage! Coating is a toolfor reference , ensuring code quality.

100% coverage does not result in "100% code quality"!



You get code quality by trying to "get it right".

The "right thing" here is not aiming for 100% coverage.

I think you won't achieve this goal without turning to PowerMock (ito). And how to avoid PowerMock (ito) is a good thing in itself - my suggestion is: just admit that you can't get 100% coverage for this class.

If at all, I would spend my time trying to exclude this class from coverage runs.

+1


source







All Articles