如何解决LocalDateTime.of 在测试类中返回 null
我有一个带有 formatToSpecificText(inputDate: LocalDateTime)
方法的类,可以将日期更改为文本。在这个方法中,我使用了 Duration.between(LocalDateTime.Now(),inputDate)
函数。我的函数返回具有持续时间的指定文本,例如“超过三天”。
我想为这个类和方法编写单元测试。在这种情况下,我想使用 @RunWith(Parametrized::class)
注释。我的测试类看起来像这样:
@RunWith(Parameterized::class)
internal class DateTest(private val case: TestCase) {
private val resources = mock<Resources>()
private val dateFormatter = mock<DateFormatter>()
private lateinit var binder: DateBinder
private val mockedNow: LocalDateTime = LocalDateTime.of(2021,Month.JULY,21,12,0)
@Before
fun setUp() {
binder = DateBinder(resources,dateFormatter)
whenever(
resources.getQuantityString(
R.plurals.over_day,1,1
)
).thenReturn(OVER_1_DAY_LABEL)
}
@Test
fun `should return formatted time string`() {
mockStatic(LocalDateTime::class.java).use { mocked ->
mocked.`when`<Any> { LocalDateTime.Now() }.thenAnswer { mockedNow }
val result = binder.formatToSpecificText(case.given)
assertthat(case.expected).isEqualTo(result)
}
}
private companion object {
const val OVER_1_DAY_LABEL = "over 1 day"
@JvmStatic
@Parameters(name = "{index}: Test with input={0}")
fun testCases(): List<TestCase> = listof(
TestCase(
given = LocalDateTime.of(2021,22,0),expected = OVER_1_DAY_LABEL
)
)
}
internal data class TestCase(
val given: LocalDateTime,val expected: String
)
}
我在 testCases 方法的给定字段中输入的所有内容在 binder.formatToSpecificText() 中都返回 null。
java.lang.NullPointerException
at java.base/java.time.LocalDateTime.until(LocalDateTime.java:1686)
at java.base/java.time.Duration.between(Duration.java:488)
at com.example.DateBinder.formatToSpecificText(DateBinder.kt:17)
我做错了什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。