문제

A coworker was trying to write a test over two static methods where one static method called the other.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ProcessUtil.class, ImageConverter.class })
public class ImageConverterTest {

    private static final Logger log = Logger.getLogger(ImageConverterTest.class.getName());

    @Test
    public void getImageMagicVersion() throws Exception {
        PowerMockito.mockStatic(ProcessUtil.class);

        PowerMockito.when(
                ProcessUtil.execAndReturnResult(Matchers.eq(new String[] { "/usr/bin/convert", "--version" })))
                .thenReturn(OLD_IMAGE_MAGIC);

        String version = ImageConverter.getImageMagicVersion();

        verifyStatic();

        ProcessUtil.execAndReturnResult(new String[] { "/usr/bin/convert", "--version" });

        log.info("Image magic version: " + version);
        assertEquals(version, OLD_IMAGE_MAGIC);
    }
}

OLD_IMAGE_MAGIC is a static final string.

When we look at ImageConverter.getImageMagicVersion all that it does is build the string array and pass it into ProcessUtil.execAndReturnResult. If ProcessUtil.execAndReturnResult is not mocked and runs I expect an exception.

Neither ProcessUtil nor ImageConverter are final, they are both standard classes with all static methods on them.

The problem we are seeing is that the version being returned is null, yet I can also verify the call on the static method as being done and correct. When I call ProcessUtil.execAndReturnResult inside of the test, it returns the correct value.

The version of PowerMock being used is 1.5.4 and we are using it in conjunction with Mockito (though such isn't relevant in this code sample) and JUnit 4.11. Any ideas about what we might be doing wrong that would lead to this sort of outcome?

도움이 되었습니까?

해결책

We determined the problem.

PowerMock was treating the following as different:

ProcessUtil.execAndReturnResult(String [] values)

and

ProcessUtil.execAndReturnResult(String... values)

The problem was that we weren't using a varArg matcher, but rather a straight array match. Switching to a vararg matcher (or switching to different data type) fixed the problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top