我正在嘗試測驗有效性功能。我的功能是這樣的:
class InvalidCredentialException(message: String) : Exception(message)
@Throws
fun credentialValidityChecker(email: String, password: String, nameAndFamily: String? = null) {
when {
email.isBlank() -> {
throw InvalidCredentialException("Email address can't left blank.")
}
!Patterns.EMAIL_ADDRESS.matcher(email)
.matches() -> {
throw InvalidCredentialException("Email address format is not correct.")
}
password.isBlank() -> {
throw InvalidCredentialException("Password can't left blank.")
}
password.length < 5 -> {
throw InvalidCredentialException("Password should have at least 5 characters.")
}
nameAndFamily != null -> {
if (nameAndFamily.isBlank())
throw InvalidCredentialException("Name and family can't left blank.")
}
}
}
如果用戶憑據出現任何問題,我會使用此函式進行拋出。否則,什么也不會發生,代碼繼續。例外在其他應用程式層中處理。這是我的測驗用例:
class CredentialValidityTest {
@Test
fun emptyEmail_raiseEmptyEmailException() {
try {
credentialValidityChecker(email = "", password = "12345")
fail("Empty email should raise exception.")
} catch (e: InvalidCredentialException) {
assertThat(e.message).isEqualTo("Email address can't left blank.")
}
}
@Test
fun wrongFormatEmail_raiseWrongEmailException() {
val wrongFormatEmailList = listOf(
"test", "test@", "test@application",
"test@application.", "test@.", "test.application@com"
)
for (email in wrongFormatEmailList)
try {
credentialValidityChecker(email = email, password = "12345")
fail("Wrong format email should raise exception.")
} catch (e: InvalidCredentialException) {
assertThat(e.message).isEqualTo("Email address format is not correct.")
}
}
@Test
fun emptyPassword_raiseEmptyPasswordException() {
try {
credentialValidityChecker(email = "[email protected]", password = "")
fail("Empty password should raise exception.")
} catch (e: InvalidCredentialException) {
assertThat(e.message).isEqualTo("Password can't left blank.")
}
}
@Test
fun weakPassword_raiseWeakPasswordException() {
try {
credentialValidityChecker(email = "[email protected]", password = "1234")
fail("weak password should raise exception.")
} catch (e: InvalidCredentialException) {
assertThat(e.message).isEqualTo("Password should have at least 5 characters.")
}
}
@Test
fun emptyNameAndFamily_raiseEmptyNameAndFamilyException() {
try {
credentialValidityChecker(
email = "[email protected]",
password = "12345",
nameAndFamily = ""
)
fail("Empty name and family should raise exception.")
} catch (e: InvalidCredentialException) {
assertThat(e.message).isEqualTo("Name and family can't left blank.")
}
}
}
問題是:
只有第一個測驗用例通過,它檢查電子郵件不為空。其他測驗用例因java.lang.NullPointerException錯誤而失敗。問題是什么?
uj5u.com熱心網友回復:
嘗試使用PatternsCompat.EMAIL_ADDRESS而不是Patterns.EMAIL_ADDRESS
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434127.html
上一篇:不應該通過的測驗
