Initialize private fields in JUnit

Viewed 5737

How do initialize private fields in JUnit so that when I test a method, the value of the private field will be used. As you can see, the private String searchDate is used in the GetSkillListServiceCustomize, but the searchDate is not initialize yet so the testing fails. I tried using reflection but it throws a NoSuchFieldException:. GetSkillListServiceCustomizeTest.class is my JUnit class while the other is the class I'm testing.

GetSkillListServiceCustomizeTest.class

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
3 Answers
Related