LoginSignup
1
0

More than 3 years have passed since last update.

[Android] テスト時のSimpleDateFormatの取り扱いで気をつけること [メモ]

Posted at

日付を取り扱う時にSimpleDateFormatを使っていたのですが、テストする時にローカルでは通っているのにGitHubActionのUnitTestでエラーを吐いてしまう。

原因

テストしたいViewModelとTestコードはこちら

class MainViewModel : ViewModel() {

    fun getDate(): String {
        val sdf = SimpleDateFormat("yyyyMMdd HH:mm", Locale.JAPAN).apply {
            this.timeZone = TimeZone.getTimeZone("Asia/Tokyo")
        }
        return sdf.format(DateUtil.getCurrentDate())
    }
}

object DateUtil {
    fun getCurrentDate() = Date()
}
class ExampleUnitTest {

    @Test
    fun getDate() {
        val mainViewModel = MainViewModel()
        mockkObject(DateUtil)

        val sdf = SimpleDateFormat("yyyyMMdd HH:mm", Locale.JAPAN)
        val currentDate = Date()
        every { DateUtil.getCurrentDate() } returns currentDate

        assertEquals(sdf.format(currentDate), mainViewModel.getDate())
    }
}

こちらのテストはローカルでは通るのだが、、、

GitHub Actionではエラーを吐く。

分かる人はすぐに気づくと思いますが、

val sdf = SimpleDateFormat("yyyyMMdd HH:mm", Locale.JAPAN)

こいつが悪さをしていた。SimpleDateFormatLocaleを指定していてもTimeZoneはデフォルトが使用されるため、テスト対象のMainViewModelでは、明示的にTimeZoneを指定していたが、TestコードにTimeZoneを書き忘れていたのが原因みたいです。GitHub ActionのTimeZoneがUTCなので、

val sdf = SimpleDateFormat("yyyyMMdd HH:mm", Locale.JAPAN).apply {
            this.timeZone = TimeZone.getTimeZone("Asia/Tokyo")
        }

しっかりTimeZoneを指定してあげましょう。(ローカルのTimeZoneってどうやって決まってるんだろう)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0