Add samples for is(|Not|NullOr)Empty and is(|Not|NullOr)Blank functions

This commit is contained in:
Ilya Gorbunov
2019-03-12 21:35:42 +03:00
parent ed878be1f7
commit 6bc7c06038
3 changed files with 88 additions and 1 deletions
@@ -1,7 +1,7 @@
package samples.text
import samples.*
import kotlin.test.assertTrue
import kotlin.test.*
class Strings {
@@ -177,6 +177,81 @@ class Strings {
assertTrue(nonBlank === sameString)
}
@Sample
fun stringIsBlank() {
fun validateName(name: String): String {
if (name.isBlank()) throw IllegalArgumentException("Name cannot be blank")
return name
}
assertPrints(validateName("Adam"), "Adam")
assertFails { validateName("") }
assertFails { validateName(" \t\n") }
}
@Sample
fun stringIsNotBlank() {
fun validateName(name: String): String {
require(name.isNotBlank()) { "Name cannot be blank" }
return name
}
assertPrints(validateName("Adam"), "Adam")
assertFails { validateName("") }
assertFails { validateName(" \t\n") }
}
@Sample
fun stringIsNullOrBlank() {
fun validateName(name: String?): String {
if (name.isNullOrBlank()) throw IllegalArgumentException("Name cannot be blank")
// name is not nullable here anymore due to a smart cast after calling isNullOrBlank
return name
}
assertPrints(validateName("Adam"), "Adam")
assertFails { validateName(null) }
assertFails { validateName("") }
assertFails { validateName(" \t\n") }
}
@Sample
fun stringIsEmpty() {
fun markdownLink(title: String, url: String) =
if (title.isEmpty()) url else "[$title]($url)"
// plain link
assertPrints(markdownLink(title = "", url = "https://kotlinlang.org"), "https://kotlinlang.org")
// link with custom title
assertPrints(markdownLink(title = "Kotlin Language", url = "https://kotlinlang.org"), "[Kotlin Language](https://kotlinlang.org)")
}
@Sample
fun stringIsNotEmpty() {
fun markdownLink(title: String, url: String) =
if (title.isNotEmpty()) "[$title]($url)" else url
// plain link
assertPrints(markdownLink(title = "", url = "https://kotlinlang.org"), "https://kotlinlang.org")
// link with custom title
assertPrints(markdownLink(title = "Kotlin Language", url = "https://kotlinlang.org"), "[Kotlin Language](https://kotlinlang.org)")
}
@Sample
fun stringIsNullOrEmpty() {
fun markdownLink(title: String?, url: String) =
if (title.isNullOrEmpty()) url else "[$title]($url)"
// plain link
assertPrints(markdownLink(title = null, url = "https://kotlinlang.org"), "https://kotlinlang.org")
// link with custom title
assertPrints(markdownLink(title = "Kotlin Language", url = "https://kotlinlang.org"), "[Kotlin Language](https://kotlinlang.org)")
}
@Sample
fun commonPrefixWith() {
assertPrints("Hot_Coffee".commonPrefixWith("Hot_cocoa"), "Hot_")