How to make unit test code that uses Java UUID?

I have a piece of code that is expected to fire a single attribute of a response object with Java UUID ( UUID.randomUUID()).

How can I unit test use this code externally to test this behavior? I do not know the UUID that will be created inside it.

Example code to test:

// 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;
}
+4
source share
3 answers

Powermock and static mockery are 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 that a static layout can be implemented in a method annotated with @Before, so it can be reused in all test cases that require a UUID to avoid repeating the code.

UUID - :

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

, , UUID, , - , @PrepareForTesting:

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

, / . , , , - - , .

/ - . , mocks.

+1

All Articles