如何初始化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
嘗試採取尾隨空間的字段名稱。 –
爲什麼你不在構造函數中初始化它?爲什麼你需要測試你甚至沒有初始化的變量? –
,因爲searchDate字段的初始化是在另一個方法中完成的,該方法將在上面所寫的方法中傳遞。這就是爲什麼,我正在尋找一種方法來爲searchDate字段設置一個虛擬值,該字段將在'.compareTo'執行時使用。 – KaelJasper