Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is part of my blog post on TDD for Android demonstrating some tests we may write.
class PokemonDetailViewModel {
private var pokemon: Pokemon? = null
fun setPokemon(pokemon: Pokemon) {
val typeCount = pokemon.types.size
if (typeCount <= 0 || typeCount > 2) {
throw IllegalArgumentException("Pokemon has an invalid number of types.")
}
this.pokemon = pokemon
}
val pokemonName: String
get() = this.pokemon?.name.orEmpty()
val firstType: String
get() = this.pokemon?.types?.first().orEmpty()
val secondType: String?
get() = this.pokemon?.types?.getOrNull(1)
val showSecondType: Boolean
get() = this.secondType != null
}
class PokemonDetailViewModelTest {
@Test
fun uninitializedPokemonReturnsDefaultValues() {
val viewModel = PokemonDetailViewModel()
assertEquals("", viewModel.pokemonName)
assertEquals("", viewModel.firstType)
assertNull(viewModel.secondType)
assertFalse(viewModel.showSecondType)
}
@Test
fun pokemonWithNoTypesThrowsException() {
val viewModel = PokemonDetailViewModel()
val testPokemon = Pokemon(name = "Squirtle")
try {
viewModel.setPokemon(testPokemon)
fail("IllegalArgumentException was expected.")
} catch (e: IllegalArgumentException) {
// TODO: This is fine, we wanted this.
}
}
@Test
fun pokemonWithOneTypeExposesOnlyThatType() {
val viewModel = PokemonDetailViewModel()
val testPokemon = Pokemon(
name = "Squirtle",
types = listOf("Water")
)
viewModel.setPokemon(testPokemon)
assertEquals("Squirtle", viewModel.pokemonName)
assertEquals("Water", viewModel.firstType)
assertNull(viewModel.secondType)
assertFalse(viewModel.showSecondType)
}
@Test
fun pokemonWithTwoTypesExposesBothTypes() {
val viewModel = PokemonDetailViewModel()
val testPokemon = Pokemon(
name = "Bulbasaur",
types = listOf("Grass", "Poison")
)
viewModel.setPokemon(testPokemon)
assertEquals("Bulbasaur", viewModel.pokemonName)
assertEquals("Grass", viewModel.firstType)
assertEquals("Poison", viewModel.secondType)
assertTrue(viewModel.showSecondType)
}
@Test
fun pokemonWithMoreThanTwoTypesThrowsException() {
val viewModel = PokemonDetailViewModel()
val testPokemon = Pokemon(
name = "Squirtle",
types = listOf("One", "Two", "Three")
)
try {
viewModel.setPokemon(testPokemon)
fail("IllegalArgumentException was expected.")
} catch (e: IllegalArgumentException) {
// TODO: This is fine, we wanted this.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.