尝试从 junit 访问 worklight.properties 时出现空异常

Null Exception when trying to access worklight.properties from junit

使用 MobileFirst Platform 6.3。

当我尝试使用 junit 从 worklight.properties 获取工作灯项目中服务器文件夹的配置路径时,值 returned 为空。

我正在使用以下代码获取路径。

WorklightConfiguration.getInstance().getString("mbaas.configRootDir");

编辑:这就是我想要做的。我是运行这段junit中的代码,应该returntrue.

public class Test2 {
    @Test 
    public void test() { 
        //customProperty=123 
        String str=getWorklightProperty("customProperty"); 
        assertEquals("123", str);
    }

    public String getWorklightProperty(String propertyName) {
        return WorklightConfiguration.getInstance().getString(propertyName);
    }
}

编辑:这不适用于 JUnit。当您 运行 这段代码时,它应该连接到一个 Worklight Server。

当您通过调用适配器 运行 它时,它会与服务器通信,这就是您可以获得响应的原因。

当您直接 运行 它时,它没有可与之通信的服务器,这就是您得到 null.

的原因

您需要验证您的代码是否有效。
我在 MFP 6.3 中测试了以下内容,并成功地从 worklight.properties:

中检索了值
  1. 在server/conf/worklight.properties中添加了最下面的属性:

    customProperty=123
    
  2. 在 server/conf/java 中创建了一个新的 Java class:

    package com.myClass.customcode;
    
    import com.worklight.server.bundle.api.WorklightConfiguration;
    
    public class Test {
        public static String getWorklightProperty(String propertyName){
            return WorklightConfiguration.getInstance().getString(propertyName); 
        }
    }
    
  3. 在 -impl.js 文件中创建了一个新的 HTTP 适配器:

    function test() {
        return {
            result: com.myClass.customcode.Test.getWorklightProperty("customProperty")
        }
    }
    

调用过程 "test" 后,响应为:

    {
       "isSuccessful": true,
       "result": "123"
    }

您正在尝试对一些通常在 Worklight Server 环境中 运行 的代码进行单元测试,这取决于

WorklightConfiguration.getInstance().getString(propertyName); 

并且只有在 运行 作为独立单元测试(例如 JUnit)时才能在服务器内部运行。

如何解决?首先,你到底想测试什么?您真的要测试 WorklightConfiguration.getInstance().getString() 是否有效?你为什么要做这样的事?您是否建议测试每个 Worklight API?我声称您应该对代码进行单元测试,而不是 Worklight。所以如果你有这样的伪代码:

  figure out the name of a property
  WorklightConfiguration.getInstance().getString(thePropertyWeJustFigured)
  do some stuff with the value we obtained

然后您可以通过提供 WorklightConfiguration API 的模拟实现来对您的代码进行单元测试。您可以使用 JMock 等框架,然后您的代码将在 JUnit 内执行,而不依赖于 Worklight。这才是真正的单元测试,没有依赖的测试。

个人不太喜欢这种方式,准备Mocks的工作量比较大。相反,我更喜欢进行结构化集成测试。也就是说,我将适配器作为一个整体进行测试,而它 运行s 在 Worklight 服务器中。我可能仍然使用 JUnit,但它 运行 的测试使用 HTTP 调用框架来调用适配器。所以测试脚本是:

 ensure worklight server is running and adapter under test is deployed
 run JUnit tests that issue HTTP requests to the adapter and inspect the results.