在JUnit中初始化私有字段

在JUnit中初始化私有字段

问题描述:

如何初始化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

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"); 
} 

我建议初始化在类的构造函数私有字段。

我会建议为这个字段创建一个setter,并发表评论,这个setter仅用于单元测试。