class CalendarViewModel : ViewModel() {
fun isHoliday(context: Context, targetDate: LocalDate): Boolean {
val targetCountry = Country.valueOf(Locale.current) // Countryは独自クラスです(コードは後述)
val targetDateString =
targetDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
try {
val inputStream = context.assets.open(targetCountry.getAssetsDirectory(targetDate))
inputStream.bufferedReader().use { reader ->
var line = reader.readLine()
while (line != null) {
val holidayDateString = line.split(",").first()
if (holidayDateString == targetDateString) {
return true
}
line = reader.readLine()
}
}
} catch (e: Exception) {
// TODO とりあえず起動を優先
println(e)
}
return false
}
}
テスト対象のメソッドで使っている独自クラス
Countryクラス
import androidx.compose.ui.text.intl.Locale
import java.time.LocalDate
enum class Country {
JA,
AU,
US;
companion object {
fun valueOf(locale: Locale): Country {
return when (locale.region) {
"JP" -> JA
"AU" -> AU
else -> US
}
}
}
fun getAssetsDirectory(date: LocalDate): String {
val prefix = when (this) {
JA -> "ja"
AU -> "au"
else -> "us"
}
return "holidays/${date.year}/holidays-${prefix}.csv"
}
}
テスト対象のメソッドの呼び出しもと
val isHoliday = CalendarViewModel().isHoliday(LocalContext.current, LocalDate.of(2024,1,1))
build.gradleを書き換えると、AndroidStudioの上の方に Gradle files have changed うんたらのメッセージが出てくると思うので、Sync をクリックすれば大丈夫です。
ParamterizedTestの記述
1. テストのファイルを用意する
テスト対象のメソッドを右クリックし、Generate... を選択して Testを選択後、特にいじらずOKってやれば大丈夫です。
自分の場合、以下のスクリーンショットのようにJUnit5 library not found in the module ってメッセージが出ているのですが、前述の導入2で設定はしているので「Fix」は押さずにやっています。