2015-02-11 65 views
0

我正在使用以下片段this答案。反思改变私人静态最终字段的值为单元测试

static void setFinalStatic(Field field, Object newValue) throws Exception { 
    field.setAccessible(true); 

    // remove final modifier from field 
    Field modifiersField = Field.class.getDeclaredField("modifiers"); 
    modifiersField.setAccessible(true); 
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); 

    field.set(null, newValue); 
} 

这里是我的MyClassTest的一部分调用上述方法。(pathToFileMyClass私人静态最终字段)。

public static void main (String ... args) { 
     try{ 
      setFinalStatic(MyClass.class.getDeclaredField("pathtoFile"), "test-propFile.properties"); 
      System.out.println(MyClass.class.getDeclaredField("pathtoFile"));// prints the original value of pathToFile. 
// how do I access the modified value pathToFile here? 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 

     } 

此外,正在做这个,正确的方法来单元测试私人静态最终字段?任何意见/建议/链接表示赞赏。

+0

我认为'MyClass'与'LMSValidation'不匹配是一个错字? – 2015-02-11 18:57:29

+0

“*正在这样做,单元测试私有静态最终字段?”的正确方法是否有效?你有什么问题吗? – Pshemo 2015-02-11 18:58:13

+0

@IanRoberts:更正了它。谢谢 – KodeSeeker 2015-02-11 19:49:28

回答

0

你不测试常量。你使用它们并测试使用它们的代码。

static final double pi = 3.14... 
let calculate_circuit r = 2 pi r 

为什么要改变pi的定义?

如果您需要测试具有不同值的代码,这意味着它不是一个常量,而是配置。那么你必须重构你的代码去耦配置和使用它的代码:

mail.server = mail.myCompany.com 
send_emal(String mailServer) = .... 

,然后你可以使用不同的邮件服务器

你也许可以使用反射或更高级别的工具,如简单地测试send_email功能模拟,但它不是很方便,并可能表明由于紧密耦合将来的问题