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

醉酒当歌 提交于 2019-12-04 02:21:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/51991345/is-there-away-to-mock-uuid-in-mockito-without-using-powermock

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