简体   繁体   中英

Best practice for unit test in play2 framework

Looks unit test in play2 frameworks pretty tough for me

Because of framework's own style, many codes are written as static and tightly coupling each other.

For example,

   boolean isExample = Configuration.root().getBoolean("example.flag");

    ....

   public class Global extends GlobalSettings {
      @Override
      public void onStart(Application app) {
        Akka.system().scheduler().schedule .....
      }
   }

Starting Akka scheduling is onStarting method on concrete class of GlobalSettings and it will be fired when FakeApplication is starting.

Configuration.root() will throw NPE without running on FakeApplication.

Everything goes with static way, there is no room for Mocking.

Could you recommend any good best practice with appropriate test isolation?

Do I have to always work with integration test? (making connection with various stuff like DB, Cache, API... etc)

This was pretty tough for me as well.

Thankfully, play 2.1+ fakeapplication works a lot better than play 2.0 and I suggest you do use FakeApplication.

pause for effect....


If you really really really dont want to run fake application, this is what I did.

Create a "Shadow" configuration root, basically, reads the same file. So basically:

boolean isExample = Configuration.root().getBoolean("example.flag");

is replaced by:

boolean isExample = MyConfigurationLoader.getBoolean("example.flag");

Where:

class MyConfigurationLoader {
    public static getBoolean(String key){
        // I use a try catch but maybe better is passing a flag/variable
        // like from the ENV so System.getenv("TEST_MODE").equals("TRUE")
        try {
            return Configuration.root().getBoolean(key);
        } catch (NPE) {
            return alternativeGetBoolean(key);
        }
    }
}

Finally, break up the akka methods into smaller methods (best practice anyway) and call them individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM