首页 > 解决方案 > 模拟类返回 null 而不是数据

问题描述

在我的 Junit 测试中,我在 Junit 测试中执行以下操作:

   @Before
    public void setUp() throws Exception {

        reportQueryParams = ReportQueryParams.builder()
            .id("07")
            .build();
    }

    @Test
    public void tabSerializerTest() {
        MetricsSerializer mockMonth = mock(MetricsSerializer.class);
            when(mockMonth.getCurrentMonth()).thenReturn("July");
        String tabSeparated = mockMonth.serializeMetrics(reportQueryParams);
        String expected = new StringBuilder().append("074")
            .append("\t")
            .append("July")
            .toString();
        assertEquals(expected, tabSeparated);

}

我正在测试的功能:

public String serializeMetrics(final ReportQueryParams reportQueryParams) {
    stringJoiner = new StringJoiner("\t");
    addValueFromString(reportQueryParams.getId());
    addValueFromString(getCurrentMonth());
    return stringJoiner.toString();
}

public String getCurrentMonth() {
    DateFormat monthFormat = new SimpleDateFormat("MMMMM");
    return monthFormat.format(new Date());
}


private void addValueFromString(final String value) {
    stringJoiner.add(value);
}

我的 ReportQueryParams 类:

  public class ReportQueryParams {
        private String id;
    }

我在返回的实际数据中得到“null”,因此测试失败。我怎样才能解决这个问题?

标签: javatestingjunitnullmockito

解决方案


不要模拟您测试的对象。您所写的是“创建一个返回当月的七月的模拟对象”。但是这个模拟对象没有真正的行为,其他方法返回 null。

当你测试一个类时,你模拟了类所需的对象(为了隔离行为)而不是实际的类。在这里,您可以创建一个新的 MetricsSerializer(通过使用 new :) 并调用它的方法 serializeMethod 并与当前日期(而不是 7 月)进行比较。

不过,您编写课程的方式可能不是最好的可测试方式;)


推荐阅读