【问题标题】:How to write JUnit Testing for methods receives a String and return LocalDate? [closed]如何为方法编写 JUnit 测试接收字符串并返回 LocalDate? [关闭]
【发布时间】:2019-04-22 04:49:35
【问题描述】:

我有这个方法,我想用 JUnit 对其进行测试。它将 String 转换为 LocalDate。

public static LocalDate convertDate(String aDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        LocalDate localDate = LocalDate.parse(aDate, formatter);

        return localDate;
    }

【问题讨论】:

标签: java testing junit


【解决方案1】:

这样的代码很容易进行单元测试:您可以使用特定的字符串调用该方法,然后检查该方法返回的 LocalDate 是否符合您的期望。

【讨论】:

  • 你能给我举个例子吗?
【解决方案2】:

您的测试方法可能如下所示:

@org.junit.Test
public void test() {
    ClassUnderTest classUnderTest = new ClassUnderTest();
    LocalDate result = classUnderTest.convertDate("22-04-2019");
    assertEquals(result.getDayOfMonth(), 22);
    assertEquals(result.getMonth(), Month.APRIL);
    assertEquals(result.getYear(), 2019);
}

关于它的几个cmets:

  1. 我使用 ClassUnderTest 的一个实例。一般来说,我不喜欢在不需要时使用静态方法。在依赖于相关类的测试中,实例方法更容易模拟。

  2. 在我的例子中,我也使用日期格式“dd-MM-yyyy”。您可以根据需要更改断言。

【讨论】:

  • 我更喜欢使用 assertThat 和 hamcrest 匹配器,但您的示例应该适合新手!
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
  • 2021-06-23
相关资源
最近更新 更多