【问题标题】:Confused About Junit Test for List<Position>对 List<Position> 的 Junit 测试感到困惑
【发布时间】:2018-05-01 20:22:06
【问题描述】:

我需要为 List 编写一个测试,我可以弄清楚如何做。我尝试编写一个类似于我的 List 测试的测试,但显然,由于它们不同且不相同,因此它不起作用。这是我到目前为止所拥有的。不知道从这里去哪里。

    public void getPosition() {

    List<Positions> positionTest = new ArrayList<Positions>();

    String name = "position_1";
    ISO8601DateFormat df = new ISO8601DateFormat();
    Date asOfDate = null;
    try {
        asOfDate = df.parse("2017-01-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Double balance = 131750000.0;
    Date uploadDate = null;
    try {
        uploadDate = df.parse("2017-02-28T22:25:51Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    String username = "admin";
    String filename = "position.xlsx";
    Integer loanCount = 2889;

    Positions p = new Positions(name, asOfDate, balance, uploadDate, username, filename, loanCount);

    positionTest.add(p);
    Mockito.when(scenarioDashboardService.getPostionFileSummaryData());
}

@Test
public void testgetPostionFileSummaryData() {

    getPosition();

    List<Positions> testPositions = scenarioDashboardService.getPostionFileSummaryData();
    assertEquals(1, testPositions.size());

    Date uploadDate = testPositions.get(0).getUploadDate();
    assertEquals("position_1", uploadDate);
}

我想从测试中获取一个日期,然后查看该日期是否与我为测试创建的日期匹配。我打算在测试中写一个字符串,但因为我的输出是一个日期,所以不能。

【问题讨论】:

  • 如果可以避免的话,我不能更强烈地建议不要使用旧版 java.util.Date。相反,您应该在 java.time 包中查找适合您用例的类(在您的情况下为 ZonedDateTimeInstant)。

标签: java list junit position junit4


【解决方案1】:

您可以将ISO8601DateFormat df = new ISO8601DateFormat(); 设为测试类的属性,然后在getPosition() 方法和测试方法中使用它。 并替换

assertEquals("position_1", uploadDate);

Date expectedDate = df.df.parse("2017-02-28T22:25:51Z");
assertEquals(expectedDate, uploadDate);

您甚至可以在"2017-02-28T22:25:51Z" 中使用String 常量来设置getPositions() 和测试方法中的常量。

【讨论】:

  • 我不能这么写,因为 uploadDate 在测试用例中不是一个变量。这是在 Position.class 中,但它不会识别。
  • @nico43624 你从你的对象uploadDate 得到Date uploadDate = testPositions.get(0).getUploadDate();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2019-09-13
  • 2012-07-22
  • 2013-05-13
  • 2020-04-16
  • 2023-03-08
相关资源
最近更新 更多