I want to mock an object that has a uuid value but I don't want to install powermock.
Your easiest way to achieve this will be to wrap up your UUID generation.
Suppose you have a class using UUID.randomUUID
public Clazz MyClazz{
public void doSomething(){
UUID uuid = UUID.randomUUID();
}
}
The UUID geneartion is completely tied to the JDK implementation. A solution would to be wrap the UUID generation that could be replaced at test time with a different dependency.
Spring has an interface for this exact senario, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/IdGenerator.html
I'm not suggesting you use Spring for this interface just informational purposes.
You can then wrap up your UUID generation,
public class MyClazz{
private final idGeneartor;
public MyClazz(IdGeneartor idGenerator){
this.idGenerator = idGenerator;
}
public void doSomething(){
UUID uuid =idGenerator.generateId();
}
You can then have multiple implementations of UUID geneartion depending on your needs
public JDKIdGeneartor implements IdGenerator(){
public UUID generateId(){
return UUID.randomUUID();
}
}
And a hardcoded impl that will always return the same UUID.
public HardCodedIdGenerator implements IdGenerator(){
public UUID generateId(){
return UUID.nameUUIDFromBytes("hardcoded".getBytes());
}
}
At test time you can construct your object with the HardCodedIdGeneartor allowing you to know what the generated ID will be and assert more freely.
I used to use MockedStatic
with JUnit 5 like this:
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.MockedStatic;
import java.util.UUID;
@ExtendWith(MockitoExtension.class)
public class MyTest {
private static MockedStatic<UUID> mockUuid;
private static final UUID constUuid = UUID.randomUUID();
@InjectMocks
private MyClass myClass;
@BeforeEach
public void setUp() {
mockUuid = mockStatic(UUID.class);
mockUuid.when(UUID::randomUUID).thenReturn(constUuid);
}
@AfterEach
public void closeResources() {
mockUuid.close();
}
@Test
public void testMyMethod() {
...
}
}
with this you can be sure your "random" UUID will always be equal to constUuid
, meaning whenever your methods call UUID.randomUUID()
, it will always return the same value. So, in your test you can assume that
@Test
public void testMyMethod() {
assertEquals(constUuid, myClass.myMethod());
}
of course, if the method, e.g. just returns the generated value
import java.util.UUID;
public class MyClass {
public UUID myMethod() {
return UUID.randomUUID();
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With