import khoury.EnabledTest import khoury.runEnabledTests import khoury.testSame // when with an enumeration enum class TrafficLight { RED, YELLOW, GREEN, } // can a car drive given the US light color? fun canDrive(current: TrafficLight): Boolean { return when (current) { TrafficLight.RED -> false TrafficLight.YELLOW -> true TrafficLight.GREEN -> true } } @EnabledTest fun testCanDrive() { // captures one example of each distinct input, // also each distinct output testSame( canDrive(TrafficLight.RED), false, "red" ) testSame( canDrive(TrafficLight.YELLOW), true, "yellow" ) testSame( canDrive(TrafficLight.GREEN), true, "green" ) } // when with a sealed class sealed class Author { // don't know :( object Unknown: Author() // known human data class FullName( val firstName: String, val lastName: String ): Author() // tricksy! data class Pseudonym( val knownAs: FullName, val realName: FullName ): Author() } val authorUnknown: Author = Author.Unknown val authorCarl: Author = Author.FullName("hank", "green") val fullNameMW = Author.FullName("mary", "westmacott") val fullNameAC = Author.FullName("agatha", "christie") val authorACMW: Author = Author.Pseudonym( knownAs = fullNameMW, realName = fullNameAC, ) // converts a full name value to the corresponding // string with first and last name fun fNToString(fullName: Author.FullName): String { return "${ fullName.firstName } ${ fullName.lastName }" } @EnabledTest fun testFNToString() { // infinite possibilities, so at least two testSame( fNToString(fullNameMW), "mary westmacott", "mw" ) testSame( fNToString(fullNameAC), "agatha christie", "ac" ) } // greets the supplied author fun getGreeting(a: Author): String { return "hi " + when (a) { is Author.Unknown -> "unknown" is Author.FullName -> fNToString(a) is Author.Pseudonym -> "${ fNToString(a.realName) } (known as ${ fNToString(a.knownAs) })" } } @EnabledTest fun testGetGreeting() { // captures at least two, // including one each of the // types of Author testSame( getGreeting(authorUnknown), "hi unknown", "unknown" ) testSame( getGreeting(authorCarl), "hi hank green", "full name" ) testSame( getGreeting(authorACMW), "hi agatha christie (known as mary westmacott)", "pseudonym" ) } fun main() { } runEnabledTests(this) main()