如何使用JUnit4测试Exception



这里有一个将字符串转换为货币格式的简单函数。

fun String.toCurrency(): String{
return try {
DecimalFormat("###,###").format(this.replace(",","").toInt())
} catch (E: NumberFormatException) {
this
}
}

我想测试一下这个方法。所以,我做了

@Test(expected = NumberFormatException::class)
@Throws(NumberFormatException::class)
fun convertCurrency_returnAmericanFormat() {
val currentList = listOf("0", "1", "10", "100", "1000", "10000", "100000", "1000000", "100000000")
val expectedList = listOf("0", "1", "10", "100", "1,000", "10,000", "100,000", "1,000,000", "100,000,000")
currentList.forEachWithIndex { i, s ->
assertEquals(expectedList[i], s.toCurrency())
}
val exceptionList = listOf("!", "@")
exceptionList.forEach {
try {
it.toCurrency()
}catch (e: NumberFormatException){
assertEquals(NumberFormatException::class, e)
}
}
}

它不起作用,显示出失败。

如何通过测试用例?我不需要检查消息,只需要检查ExceptionClass。

toCurrency扩展函数中,捕获数字格式异常并返回原始字符串。您应该重新抛出异常,或者根本不捕获它。

// ...
catch(e: NumberFormatException) {
// log the exception or ...
throw e 
}

在这里,让我们只测试toCurrency方法的无效场景。很容易确定哪个测试场景失败或成功。

@Test
fun convertCurrency_invalidNumbers_throwsException() {
val invalidCurrencies = listOf("!", "@")
// check also for big numbers -> 999999999999
assertThrows<NumberFormatException> {
invalidCurrencies.forEach {
it.toCurrency()
}
}
}
@Test
@Throws(NumberFormatException::class)
fun convertCurrency_returnAmericanFormat() {
// test for successful toCurrency conversion
}

相关内容

最新更新