问题描述
我想模拟一个具有uuid值的对象,但是我不想安装powermock.
I want to mock an object that has a uuid value but I don't want to install powermock.
推荐答案
您最简单的方法是包装UUID生成.
Your easiest way to achieve this will be to wrap up your UUID generation.
假设您有一个使用UUID.randomUUID
public Clazz MyClazz{
public void doSomething(){
UUID uuid = UUID.randomUUID();
}
}
UUID源代码完全与JDK实现联系在一起.一种解决方案是包装UUID生成,可以在测试时用不同的依赖项替换它.
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具有针对此确切参数的接口, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/IdGenerator.html
Spring has an interface for this exact senario, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/IdGenerator.html
我不建议您仅出于参考目的将Spring用于此界面.
I'm not suggesting you use Spring for this interface just informational purposes.
然后您可以打包UUID代,
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();
}
然后,您可以根据自己的需要实现UUID创世记的多种实现方式
You can then have multiple implementations of UUID geneartion depending on your needs
public JDKIdGeneartor implements IdGenerator(){
public UUID generateId(){
return UUID.randomUUID();
}
}
还有一个硬编码的impl,它将始终返回相同的UUID.
And a hardcoded impl that will always return the same UUID.
public HardCodedIdGenerator implements IdGenerator(){
public UUID generateId(){
return UUID.nameUUIDFromBytes("hardcoded".getBytes());
}
}
在测试时,您可以使用HardCodedIdGeneartor构造对象,让您知道生成的ID是什么并更自由地断言.
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.
这篇关于是否可以在不使用powermock的情况下在Mockito中模拟UUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!