我有一个有一个学生的班级 formatToSpecificText(inputDate: LocalDateTime)
方法将日期更改为文本。在这个方法中,我使用 Duration.between(LocalDateTime.now(), inputDate)
功能。my函数返回具有持续时间的指定文本,例如“超过三天”。
我想为这个类和方法编写单元测试。在这种情况下,我想使用 @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, 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, Month.JULY, 22, 12, 0, 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)
我做错了什么?
暂无答案!
目前还没有任何答案,快来回答吧!