预期结果为< 0>。而不是日期

时间:2018-05-02 14:46:40

标签: java date junit junit4

我有这个Junit测试,我正在尝试写日期。单元测试用于的代码是返回日期的函数。下面我有我为代码编写的内容。

    public void getLatestHistoricalLossDate() {

    List<Overview> scenarioListTest3 = new ArrayList<Overview>();

    String name = "third_scenario-test";
    ISO8601DateFormat df = new ISO8601DateFormat();
    Date estimationDate = null;
    try {
        estimationDate = df.parse("2017-01-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Date creationDate = null;
    try {
        creationDate = df.parse("2017-02-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Double balance = 131750000.0;
    Double individualReviewImpairment = 1000.00;
    Map<String, Double> baseline = new HashMap<String, Double>();
    baseline.put("complete", 1000.0);

    Map<String, Double> macroAdjustment = new HashMap<String, Double>();
    macroAdjustment.put("complete", 2000.0);

    Map<String, Double> qualitativeAdjustment = new HashMap<String, Double>();
    qualitativeAdjustment.put("complete", 3000.0);

    Date positionDate = null;
    try {
        positionDate = df.parse("2017-01-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Date lossHistoryDate = null;
    try {
        lossHistoryDate = df.parse("2017-01-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    String status = "active";

    Map<String, Integer> period = new HashMap<String, Integer>();
    period.put("Q1", 2017);

    boolean publish = true;

    Overview ac = new Overview(4, name, estimationDate, creationDate, balance, individualReviewImpairment, baseline,
            macroAdjustment, qualitativeAdjustment, positionDate, lossHistoryDate, status, period, publish);

    scenarioListTest3.add(ac);

    Mockito.when(scenarioDashboardService.getLatestHistoricalLossDate()).thenReturn(lossHistoryDate);
}

@Test
public void testgetLatestHistoricalLossDate() throws Exception {

    getLatestHistoricalLossDate();

    ISO8601DateFormat df = new ISO8601DateFormat();
    Date testLossHistoryDate = scenarioDashboardService.getLatestHistoricalLossDate();
    assertEquals(df.parse("2017-01-28T22:25:51Z"), testLossHistoryDate);
    int expectedHistoricalDate = testLossHistoryDate.compareTo(testLossHistoryDate);
    Date lossHistoricalDate = df.parse("2017-01-28T22:25:51Z");
    assertEquals(expectedHistoricalDate, lossHistoricalDate);
}

当我运行测试时,它表明预期的结果是0而不是列出的日期,我不明白为什么。通常我会将assertEquals()语句设为assertEquals(1, testLossHistoryDate.size());,但.size不适用于日期。有人知道做同样事情的不同方法吗?

1 个答案:

答案 0 :(得分:1)

    assertNotNull(testLossHistoryDate);

这会检查是否只有一个日期。

由于你的方法的返回类型是Date,因此它不能返回多个Date。然而,它可以返回null,即根本没有日期;但如果发生这种情况并且未通过测试,上述断言将会发现。

PS java.util.Date很久了。您可以自己寻找现代Java日期和时间API java.time。与它合作真是太好了。 链接: Oracle Tutorial: Date Time