0

使用 MobileFirst 平台 6.3。

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

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

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

编辑:这就是我想要做的。我在 junit 中运行这段代码,它应该返回true.

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);
    }
}
4

2 回答 2

0

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

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

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


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

  1. 在 server/conf/worklight.properties 的最底部添加了以下属性:

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

    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"
    }
于 2015-01-13T14:54:45.447 回答
0

您正在尝试对通常在 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 的 Mock 实现来对您的代码进行单元测试。您可以使用 JMock 等框架,然后您的代码将在 JUnit 中执行而无需依赖 Worklight。这是真正的单元测试,没有依赖关系的测试。

我个人不太喜欢这种方法,准备 Mocks 的工作量很大。相反,我更喜欢进行结构化集成测试。也就是说,我将适配器作为一个整体进行测试,同时它在 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.
于 2015-01-27T15:43:53.760 回答