简体   繁体   English

Play2框架中单元测试的最佳实践

[英]Best practice for unit test in play2 framework

Looks unit test in play2 frameworks pretty tough for me 在play2框架中看起来单元测试对我来说很难

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. 启动Akka调度是针对GlobalSettings具体类的onStarting方法,并且在FakeApplication启动时将被触发。

Configuration.root() will throw NPE without running on FakeApplication. Configuration.root()将抛出NPE而不在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) (与各种内容(例如DB,Cache,API等)建立连接

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. 幸运的是,玩2.1+的fakeapplication比玩2.0的要好得多,我建议您使用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. 基本上,创建一个“ Shadow”配置根目录会读取相同的文件。 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. 最后,将akka方法分解为较小的方法(无论如何都是最佳实践),然后分别调用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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