How do I unit test code which uses Java UUID?

孤街浪徒 提交于 2019-12-01 05:17:07

Powermock and static mocking is the way forward. You will need something like:

    ...
    import static org.junit.Assert.assertEquals;
    import static org.powermock.api.mockito.PowerMockito.mockStatic;
    ...

    @PrepareForTest({ UUID.class })
    @RunWith(PowerMockRunner.class)
    public class ATest
    {
    ...
      //at some point in your test case you need to create a static mock
      mockStatic(UUID.class);
      when(UUID.randomUUID()).thenReturn("your-UUID");
    ...
    }

Note the static mock can be implemented in a method annotated with @Before so it can be re-used in all test cases that require UUID in order to avoid code repetition.

Once the static mock is initialised, the value of UUID can be asserted somewhere in your test method as follows:

A a = doSomething();
assertEquals("your-UUID", a.getX());

When you need to mock, class/static methods become a real pain. What I ended up doing which will save you from using a mocking system is to use a thin wrapper class with a interface implementing the static methods.

In your code, instantiate/inject and use use the wrapper class instead of the static method. That way you can replace it with mocks.

In relation to this existing question, it seems like the only way I was able to get the UUID to successfully mock out is if I added the class I wanted to test under @PrepareForTesting:

@PrepareForTesting({UUIDProcessor.class})
@RunWith(PowerMockitoRunner.class)
public class UUIDProcessorTest {
    // tests
}

In addition to ThinkBonobo's response, another way it to create a getter method (optionally annotated with @VisibleForTesting) such as String getUUID() which can be overridden in a subclass you define in your test.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!