Blankman
Blankman

Reputation: 266978

Refactoring static class so I can unit test it

I have a static class that I would like to refactor so I can change the name of the properties file etc., and to be able to unit test it easier.

Current I have this:

public enum MySettings {

   INSTANCE;

   //priv vars
   private string applicationUrl;

   private MySettings() {

     MappingJsonFactory jf = new MappingJsonFactory();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream mySettingsInputStream = classLoader.getResourceAsStream("a.properties");

    Properties mySettingsProperties = new Properties().load(mySettingsInputStream);

    // code below to load json and set priv vars etc.




   }

   public String getApplicationUrl() {
       return applicationUrl;
   }
}

How could I set the name of the properties file to something else in my unit tests?

Upvotes: 0

Views: 95

Answers (2)

Martin Braun
Martin Braun

Reputation: 602

you could fiddle all the stuff from the enum class into a real instantiable class (via package protection or protected) and then make an instance of it accessible via the enum (getter). Like this you can unit test everything like a charm and also have it as a singleton :). With this you don't need a second Enum constant (as pointed out in the comments).

If you are using protected instead of package protection you can unit test it by creating a dummy class that inherits from the actual class and instantiate it in the test like this:

private static class Dummy extends NewClass {

    public Dummy() {
        super();
    }

}

Upvotes: 0

djechlin
djechlin

Reputation: 60758

"Inversion of control." The simplest way to do this here would be to take it in as a constructor arg. At the higher end would be an IOC framework, such as Spring.

Worse case since you're dealing with an enum - may need to factor out an interface then provide an implementing enum. Or better:

public enum Settings {
    PRODUCTION("prod.xml"), UNIT_TESTING("dev.xml");
    //...

Upvotes: 3

Related Questions