Powermock,UUID.getRandom的mockStatic在测试类中工作,但在测试的类中没有

时间:2018-03-04 20:43:53

标签: uuid powermock mockstatic

奇怪的情况:使用Powermock模拟UUID.getRandom()。这适用于JUnit测试类,但是当被测试的类(过滤器,如果这很重要)调用UUID.getRandom时,会生成一个唯一的UUID。

简单的测试用例

@RunWith(PowerMockRunner.class)
@PrepareForTest({UUID.class})
public class MyTest {

    private MyFilter filter;

    @Before
    public void setup() {

        //The most convenient way to get a UUID, have also tried creating one manually
        UUID uuid = UUID.randomUUID();

        mockStatic(UUID.class);

        PowerMockito.when(UUID.randomUUID()).thenReturn(uuid);

        filter = new MyFilter();
    }

    @Test
    public void testMyUUID() {

        //This test works
        assertEquals(UUID.randomUUID(), UUID.randomUUID());

    }

    @Test
    public void testFilterUUID() {

        //This test fails
        assertEquals(UUID.randomUUID(), filter.getUUID());
    }
}

正在测试的简单课程

public class MyFilter implements Filter {

    public UUID getUUID() {

        return UUID.randomUUID();
    }
}

非常简单的东西,之前做过这样的嘲讽,只是无法弄清楚为什么这个案子不起作用。

使用Powermock 1.5版。

1 个答案:

答案 0 :(得分:1)

我相信UUID属于"system classes" category,因此您需要准备测试调用UUID.randomUUID()related github issue)。的类,从而更改为{{1}应该解决问题。以下工作与JUnit 4.4& Powermock 1.5,以及JUnit 4.12和Powermock 1.7.3:

@PrepareForTest({MyFilter.class})