1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android の JUnit テストで Locale を切り替えて実行する

Posted at

TL;DR

  • Locale.setDefault(...) する

背景

  • 言語によって挙動が変わる関数の JUnit テストを書きたい
  • 例)人物の表示名を返す関数
  • 日本語の時:姓+名
  • それ以外の時:名+姓
Person.kt
data class Person(val firstName: String, val lastName: String) {
    fun displayName(): String =
            when (Locale.getDefault()) {
                Locale.JAPAN -> "$lastName $firstName"
                else -> "$firstName $lastName"
            }
}

テストコード

PersonTest.kt
class PersonTest {

    private val person = Person(firstName = "Taro", lastName = "Yamada")

    @Test
    fun displayNameTestJp() {
        Locale.setDefault(Locale.JAPAN)
        Assert.assertEquals("Yamada Taro", person.displayName())
    }

    @Test
    fun displayNameTestUs() {
        Locale.setDefault(Locale.US)
        Assert.assertEquals("Taro Yamada", person.displayName())
    }
}

結果

スクリーンショット 2017-09-16 10.27.19.png
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?