Search code examples
junitmockitopowermock

Is there away to mock UUID in Mockito without using powermock?


I want to mock an object that has a uuid value but I don't want to install powermock.


Solution

  • 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.