我有一个奇怪的案例。我正在运行一个本地测试,并在该测试中使用Calendar类。
当用@RunWith(AndroidJUnit4::class)
注释测试类时,测试通过,否则,测试失败。
测试代码不包括任何Android环境库
这是我的
class MyDateUtils(private val calendar: Calendar) {
fun getDates(): Long{
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
return calendar.timeInMillis
}
}
这是测试用例,这个通过了
@RunWith(AndroidJUnit4::class)
class MyDateUtilsTest {
private lateinit var calendar: Calendar
private lateinit var dateUtils: MyDateUtils
@Before
fun init() {
calendar = Calendar.getInstance()
calendar.timeInMillis = 1592422768000
dateUtils = MyDateUtils(calendar)
}
@Test
fun `when get dates is called with wednesday day should return sunday of the same week`() {
val expected = 1592163568000
val actual = dateUtils.getDates()
assertEquals(expected, actual)
}
}
现在,当我删除@RunWith(AndroidJUnit4::class)
时,测试失败,并显示此错误消息java.lang.AssertionError: Expected :1592163568000 Actual :1592768368000
p.S预期的行为是getDates()
方法在同一周内的周日返回。但如果没有@RunWith(AndroidJUnit4::class)
,它将在下周日(下一周(返回。
这可能与使用AndroidJUnit4运行时可能更改的默认区域设置有关。
对于不同的地区,一周的第一天是不同的,这可能会导致测试失败或通过,具体取决于跑步者。