2017-07-31 43 views
2

如何初始化JUnit中的私有字段,以便在測試方法時使用專用字段的值。如您所見,private String searchDate用於GetSkillListServiceCustomize,但searchDate尚未初始化,因此測試失敗。我嘗試使用反射,但它會拋出一個NoSuchFieldException:GetSkillListServiceCustomizeTest.class是我的JUnit類,而另一個是我正在測試的類。

GetSkillListServiceCustomizeTest.class在JUnit中初始化私有字段

try { 
      Field reader = GetSkillListServiceCustomize .class.getDeclaredField("searchDate "); 
      reader.setAccessible(true); 
      StringReader stringReader = new StringReader("2017-01-28"); 
      BufferedReader readerToSet = new BufferedReader(stringReader); 
      reader.set(testClass, readerToSet); 
      returnVal = testClass.processOutput(mapVar); 
     } catch (NoSuchFieldException e1) { 
      e1.printStackTrace(); 
     } catch (SecurityException e1) { 
      e1.printStackTrace(); 
     } 

     assertTrue(returnVal != null); 
    } 

GetSkillListServiceCustomize.class

public class GetSkillListServiceCustomize 
    extends GetSkillListService 
    implements ServiceIF<GetSkillListInputDTO, GetSkillSummaryDisplayDTO> { 

    private String searchSite; 
    private String searchDate; 

    ...more codes 

    protected GetSkillListOutputDTO processOutput(Map<String, Object> resultMap) 
      throws ServiceDBException, ServiceAppException { 

    ...//more codes 
    List<GetSkillListOutputDTOList> getskilllistoutputdtolistTmpWrap = null; 
    if (employeeMasterList != null && !employeeMasterList.isEmpty()) { 
     getskilllistoutputdtolistTmpWrap = new ArrayList<>(); 
    } 
    if (employeeMasterList != null && !employeeMasterList.isEmpty()) { 
     List<EMPLOYEE_MASTER> empMasterlistNoDeleted = employeeMasterList.stream() 
       .filter(e -> { 
        try { 
         return (e.getDel_Datetime() == null 
            || (sdf.parse(e.getDel_Datetime()) 
              .compareTo(sdf.parse(this.searchDate)) > 0)); 
        } catch (ParseException ex) { 
         ex.printStackTrace(); 
         return false; 
        } 
       }) 
       .collect(Collectors.toList()); 

     ...//more codes in the bottom 
+1

嘗試採取尾隨空間的字段名稱。 –

+0

爲什麼你不在構造函數中初始化它?爲什麼你需要測試你甚至沒有初始化的變量? –

+0

,因爲searchDate字段的初始化是在另一個方法中完成的,該方法將在上面所寫的方法中傳遞。這就是爲什麼,我正在尋找一種方法來爲searchDate字段設置一個虛擬值,該字段將在'.compareTo'執行時使用。 – KaelJasper

回答

2

JUnit爲初始化方法@Before提供標記。在init方法中,你可以初始化幾乎所有你想要的東西。要在您的測試,以私人領域有用的訪問,我會建議使用第三方utils的,例如

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-test</artifactId> 
    <version>4.3.10.RELEASE</version> 
    <scope>test</scope> 
</dependency> 

你就可以使用二傳手的私有字段是這樣的:

@Before 
public void setUp() { 
    org.springframework.test.util 
     .ReflectionTestUtils.setField(
      theGetSkillListServiceCustomizeInstance, 
      "searchSite", 
      "valueToSet"); 
} 
-2

我建議初始化在類的構造函數私有字段。

1

我會建議爲這個字段創建一個setter,並發表評論,這個setter僅用於單元測試。