我正在使用Kotlin创建一个Spring Boot应用程序。这是我用于集成测试Spring存储库的类的一部分:
@ExtendWith(SpringExtension::class)
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ImageRepositoryTest {
@Autowired
lateinit var imageRepository: ImageRepository
private val image: Image
init {
image = Image(1, "image.jpg", "/image.jpg", "http://test/image.jpg")
}
@Test
fun `refuses to store duplicated images throwing a DataIntegrityViolationException` () {
imageRepository.save(image)
assertThrows<DataIntegrityViolationException> {imageRepository.save(image)}
}
}
这是Image类的定义:
import javax.persistence.*
@Entity
@Table(name = "image")
data class Image(@Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Int,
@Column(unique = true, nullable = false) val name: String,
@Column (unique = true, nullable= false) val path: String,
@Column (unique = true, nullable= false) val url: String)
执行后,测试失败,表明没有抛出异常(应有)。但是,如果函数的名称不包含令牌“ throwing”,(例如,我将其重命名为refuses to store duplicated images raising a DataIntegrityViolationException
,则测试成功。
函数名称中似乎存在该令牌可防止其引发异常。这是预期的行为吗?
答案 0 :(得分:0)
我尝试使用以下代码重现您的问题,但一切正常:
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class ThrowsTest {
private val repository = ImageRepository()
@Test
fun `refuses to store duplicated images throwing a IllegalArgumentException`() {
assertThrows<IllegalArgumentException> {
repository.save()
}
}
}
class ImageRepository {
fun save() {
throw IllegalArgumentException("Already saved")
}
}
您如何执行测试? IntelliJ,Maven,Gradle?您是否可以简化示例,例如通过删除Spring依赖项?