【问题标题】:Set system property in jmockit unit test在 jmockit 单元测试中设置系统属性
【发布时间】:2017-05-30 14:55:51
【问题描述】:

结合使用 testng 和 jmockit 进行一些单元测试。在我正在测试的方法中,它尝试访问我使用 JBoss 部署脚本设置的系统属性,因此我的单元测试无法访问整个 JBoss 环境来访问属性,因此在测试该方法时它返回 null .尝试在我的测试中直接模拟和设置系统变量,但系统属性在我正在测试的类中仍然返回 null。

被测试的类:

//returns the correct value in the application but returns null for the test
public static final String webdavrootDir = System.getProperty("property.name");

public String getFileUrl(){
       StringBuilder sb = new StringBuilder();
       return sb.append(webdavrootDir)
               .append(intervalDir)
               .append(fileName)
               .toString();
}

测试:

@Test
    public void getUrl(@Mocked System system){
        system.setProperty("property.name", "https://justatest.com/dav/bulk");
        String fileUrl = csvConfig.getFileUrl();

        assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff");
}

测试找到值null/otherstuff,但期望值https://justatest.com/dav/bulk/otherstuff

我也尝试在 testng @BeforeMethod 方法中设置系统属性,但没有成功。

【问题讨论】:

    标签: java unit-testing testng jmockit system-properties


    【解决方案1】:

    确保在被测试的类被实例化之前调用System.setProperty("property.name", "https://justatest.com/dav/bulk");,否则静态字段将始终为空。

    考虑为此使用@BeforeClass 设置方法:

    @BeforeClass
    public static void setup() {
        System.setProperty("property.name", "https://justatest.com/dav/bulk");
        // Instantiate your CsvConfig instance here if applicable.
    }
    

    然后

    @Test
    public void getUrl(){
        System.setProperty("property.name", "https://justatest.com/dav/bulk");
        String fileUrl = csvConfig.getFileUrl();
        assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff");
    }
    

    【讨论】:

      【解决方案2】:

      如果您想使用 jMocki,但您必须确保在加载您的被测类之前完成它(因为静态字段)。

      @BeforeClass
      public static void fakeSystemProperty() {
          new MockUp<System>() {
      
              @Mock
              public String getProperty(String key) {
                  return "https://justatest.com/dav/bulk";
              }
          };
      }
      

      另一种方法是修改被测类并部分模拟这个类,例如:

      public class CsvConfig {
          private static final String webdavrootDir = System.getProperty("property.name");
      
          public static String getProperty() {
              return webdavrootDir;
          }
      }
      

      测试:

      @BeforeClass
      public static void fakeSystemProperty() {
          new MockUp<CsvConfig>() {
      
              @Mock
              public String getProperty() {
                  return "https://justatest.com/dav/bulk";
              }
          };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 2014-08-16
        • 2022-01-23
        • 2017-04-17
        • 2013-03-03
        • 2017-10-30
        相关资源
        最近更新 更多