如何测试一个LocalDate是否无效?

huangapple go评论65阅读模式
英文:

JUnit, how can i test if a LocalDate is not valid?

问题

我正在为一个大学项目进行一些测试。

我想要测试一个名为*verifyCorrectDates(LocalDate firstDate, LocalDate lastDate)*的方法。

总的来说,我认为我们可以考虑以下可能的情况:

  • 一个LocalDate为空
  • 一个LocalDate无效(例如,2023-40-40)
  • 一个LocalDate有效

由于我有两个LocalDates作为输入,所以应该有9个测试来涵盖每种情况。

问题是:我不知道如何测试这个方法,以使用一个'无效日期'。
如果我使用LocalDate.of(2023, 40, 40),它会直接报错,当然了。我开始觉得可能根本不可能插入一个无效的LocalDate。

有什么想法吗?

英文:

I'm doing some testing for a university project.

I wanted to test a method verifyCorrectDates(LocalDate firstDate, LocalDate lastDate).

In general, i think we could see these possible scenarios:

  • a LocalDate is null
  • a LocalDate is not valid (for example, 2023-40-40)
  • a LocalDate is valid

Since i have two LocalDates as input, there should be 9 test to comprehend every situation.

Thing is: i don't know how can i test this method using a 'non valid date'.
If i use LocalDate.of(2023,40,40) it simply gives me an error, of course. I'm starting to think it's simply not possible to insert a non valid LocalDate.

Any ideas?

答案1

得分: 3

您不应创建无效的LocalDate实例,因为这些实例将引发异常,因此在测试函数时不是实际可行的。您仍然可以提出有效的测试场景,例如检查函数调用的正确性,如果在以下情况下调用它:

  1. 两个日期都为null
  2. 第一个日期为null,第二个日期有效。
  3. 第一个日期有效,第二个日期为null。
  4. 两个日期都有效,且第一个日期在第二个日期之后。
  5. 两个日期都有效,且第一个日期在第二个日期之前。
  6. 日期有效,且第一个日期与第二个日期相同。
英文:

You should not create invalid LocalDate instances, as those will throw exceptions, so its not practical in case of testing your function. You can still come up with valid test scenerios, like check correctness of function call if its called when:

  1. both dates are null
  2. first date is null, the second date is valid.
  3. first date is valid, the second date is null.
  4. both dates are valid, and the first date is after the second date.
  5. both dates are valid, and the first date is before the second date
  6. dates are valid, and the first date is the same as the second date.

huangapple
  • 本文由 发表于 2023年7月11日 01:37:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定