仅使用 AndroidJunit4 时日历测试通过

calendar test passes when using AndroidJunit4 only

我有一个奇怪的案例。我是 运行 本地测试并在该测试中使用日历 class。

当用 @RunWith(AndroidJUnit4::class) 注释测试 class 时,测试通过,否则测试失败。

测试代码不包含任何Android环境库

这是我的 class

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() 方法 return 同一周内的星期日。但是 没有 @RunWith(AndroidJUnit4::class) 它 return 接下来的星期天(下一周)。

这可能与当您 运行 使用 AndroidJUnit4 时可能会更改的默认语言环境有关。

对于不同的语言环境,一周的第一天是不同的,这可能会导致测试失败或通过,具体取决于 运行ner。