Search code examples
javaunit-testingjunitdependency-injectiontestability

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.


Solution

  • You can isolate all the property retrieval in some sort of PropertyResolverBean and then inject that in your SUT's and replace the static calls:

    private PropertyResolverBean injectedPropertyResolverBean;
    
    void someMethod(Data data){
      if(injectedPropertyResolverBean.getValue("OK"))
        // Do Something
    
    }
    

    Then you can use the basic features of Mockito for example in order to mock that bean and pre-configure your tests the way you want.

    You end up with a more maintainable, readable and testable code at the end that follows the SRP rule.