How do I unit test code which uses Java UUID?

I have a piece of code which is expected to populated one attribute of response object with Java UUID (UUID.randomUUID()).

How can I unit test this code from outside to check this behaviour? I don’t know the UUID that would be generated inside it.

Sample code which needs to be tested:

// To test whether x attribute was set using an UUID
// instead of hardcode value in the response
class A {
  String x;
  String y;
}

// Method to test
public A doSomething() {
  // Does something
  A a = new A();
  a.setX( UUID.randomUUID());
  return a;
}

Answer

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());

Leave a Reply

Your email address will not be published. Required fields are marked *