java - How make code that uses global dynamic properties unit testable?
问题描述
A lot of code needs to use some global flag or properties to control the flow of the application. It is necessary for a lot of scenarios to maintain a Dynamic Cache which will have a flag to lock/unlock a particular piece of (new)code.
For all such scenarios I usually write this way:
'''
void someMethod(Data data){
if(DynamicProperty.getValue("OK"))
// Do Something
}
DynamicPropery
is a Singleton which periodically refreshes the cache from the DB.
The problem with this is Unit testing is little tricky, so far I've used Jmockit to get around that - and it works fine.
But I was wondering if there can be a better way to write a method like that that can be easier for Unit testing.
解决方案
您可以以某种方式隔离所有属性检索,PropertyResolverBean
然后将其注入您的 SUT 并替换静态调用:
private PropertyResolverBean injectedPropertyResolverBean;
void someMethod(Data data){
if(injectedPropertyResolverBean.getValue("OK"))
// Do Something
}
然后,您可以使用 Mockito 的基本功能来模拟该 bean 并以您想要的方式预配置您的测试。
您最终会得到遵循 SRP 规则的更易于维护、可读性和可测试性更高的代码。
推荐阅读
- c# - 选择不同的项目时,组合框属性更改属性不更新?
- php - 如何使用 google docs api php 插入文本
- python - 修补本地类引用
- database - 如何在 DigitalOcean droplet 上安装和启动 Exasol 社区?
- javascript - 检查 Laravel-blade 中所有复选框的好方法
- mysql - Python MySQL连接器插入,但信息实际上不在数据库中
- angular - CKEditor4 w/Angular8:工具栏中缺少按钮
- python - 与等待并行运行方法
- javascript - 承诺控制流
- reactjs - 当我尝试导入 DropDown react-native 时出错