使用JUnit在Kotlin中测试自定义异常



我有以下类

data class CarDefects(
private val _carModel: CarModel,
private val _affectedYearsOfIssue: List<Year>,
private val _defectCode: String
) {
init {
validateDefectCode(_defectCode)
}
}

验证功能

fun validateDefectCode(defectCode: String) {
val pattern = Pattern.compile("^[a-zA-Z0-9-]*$")
val m = pattern.matcher(defectCode)
if (defectCode.length !in 4..4) {
throw InvalidDefectCodeException(defectCode, "Defect code must be 4 characters long")
}
if (!m.matches()) {
throw InvalidDefectCodeException(defectCode, "Defect code can only contain alphanumeric characters")
}
}

以及异常类别:

class InvalidDefectCodeException(_defectCode:String, message:String):
IllegalArgumentException("Invalid defect code $_defectCode. $message") {
}

我正在尝试用JUnit 测试验证功能

import car.exceptions.InvalidDefectCodeException
import car.validators.carDefectsValidators.validateDefectCode
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.time.Year
import kotlin.test.assertFailsWith
internal class CarDefectsTest {
val carModel = CarModel(Brand.BMW, "X5", 199219)
val carModel2 = CarModel(Brand.AUDI, "X434", 199219)

val defect = CarDefects(carModel, listOf(Year.of(2020), Year.of(2021)), "SE2@")
val defect2 = CarDefects(carModel2, listOf(Year.of(2020), Year.of(2021)), "122F4")
@Test
fun testDefectCodeExceptions() {
val exception = Assertions.assertThrows(InvalidDefectCodeException::class.java) {
validateDefectCode(defect.getDefectCode())
}
}
@Test
fun testDefectCodeExceptions2() {
assertFailsWith<InvalidDefectCodeException> {
validateDefectCode(defect2.getDefectCode())
}
}
}

两个测试都失败了,然而预期的异常仍然抛出,根据我的理解,两个测试不应该都通过吗?

我已经看到了以下帖子:在Kotlin 中测试预期的异常

在类CarDefects中,您有这个init块:

init {
validateDefectCode(_defectCode)
}

因此,异常将在构造过程中抛出。

让我们用一个精简的CarDefects类来测试构造函数。以下测试在我的电脑上通过了。

import car.exceptions.InvalidDefectCodeException
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import kotlin.test.assertFailsWith
data class CarDefects(
private val defectCode: String
) {
init {
validateDefectCode(defectCode)
}
}
internal class CarDefectsTest {
@Test
fun testDefectCodeExceptions() {
Assertions.assertThrows(InvalidDefectCodeException::class.java) {
CarDefects(defectCode = "SE2@")
}
}

@Test
fun testDefectCodeExceptions2() {
assertFailsWith<InvalidDefectCodeException> {
CarDefects(defectCode = "122F4")
}
}
}

相关内容

  • 没有找到相关文章