0

奇怪的案例:使用 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 版。

4

1 回答 1

1

我相信UUID属于系统类”类别,因此您需要准备测试类调用UUID.randomUUID()相关的 github 问题)。因此更改为@PrepareForTest({MyFilter.class})应该解决问题。以下内容与 JUnit 4.4 和 Powermock 1.5 以及 JUnit 4.12 和 Powermock 1.7.3 一起按预期工作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyFilter.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());
    }
}
于 2018-03-05T07:27:50.633 回答