在JUnit

时间:2017-07-31 02:46:03

标签: java junit junit4

如何在JUnit中初始化私有字段,以便在测试方法时,将使用私有字段的值。如您所见,private String searchDate中使用了GetSkillListServiceCustomize,但searchDate尚未初始化,因此测试失败。我尝试使用反射,但它会抛出NoSuchFieldException:GetSkillListServiceCustomizeTest.class是我的JUnit课程,而另一个是我正在测试的课程。

 的 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 个答案:

答案 0 :(得分:3)

JUnit为init方法@Before提供标记。在init方法中,您可以初始化几乎所有您想要的东西。为了有用访问私有字段,我建议使用第三方工具,例如

<!-- 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>

在您的测试中,您可以将setter用于私有字段,如下所示:

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

答案 1 :(得分:1)

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

答案 2 :(得分:-2)

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