JUnit、@ControllerAdvice 和 Kotlin 中缺少检查异常
JUnit, @ControllerAdvice and lack of checked exceptions in Kotlin
我在 Kotlin 中写了一个 validation advisor,它在验证失败时抛出 EntityValidationException
:
@Aspect
@Named
class ValidationAdvisor
@Inject constructor(val validator: EntityValidator) {
@Around(EVERY_SAVE_AND_UPDATE_TO_DATABASE)
fun validate(point: ProceedingJoinPoint): Any {
val result: List<ConstraintViolation<Any>> = validator.validate(getEntity(point))
if (isEntityValid(result))
return point.proceed()
throw EntityValidationException(
violationInfos = result as List<ConstraintViolationInfo>
)
}
private fun getEntity(point: ProceedingJoinPoint): Any {
return point.args[0]
}
private fun isEntityValid(result: List<ConstraintViolation<Any>>): Boolean {
return result.isEmpty()
}
companion object {
const val EVERY_SAVE_AND_UPDATE_TO_DATABASE = "execution(* beans.repositories.BaseRepository.save(..))"
}
}
我有一个 JUnit 测试(我在 Kotlin 中编写了一些部分,在 Java 中编写了一些部分,以在现有的私人项目中学习 Kotlin),它检查是否抛出异常:
@Test(expected = EntityValidationException.class)
public void test_WhenNameIsNotPresent_ThenExceptionIsThrown() throws Exception {
repository.save(/* entity to save */);
}
但后来我看到测试失败,因为它抛出 UndeclaredThrowableException instead of EntityValidationException
. Next, I read that Kotlin does not have checked exception. I think not only me have this problem - I am pretty sure that way of handling exceptions with @ControllerAdvice in Spring and Java 当我们决定在生产项目中切换到 Kotlin 时也可能有问题 - 因为它依赖于抛出的 class,并且抛出UndeclaredThrowableException
剥夺了我们这种可能性。有没有办法绕过这种行为,以确保可以切换到 Kotlin 和 old Spring 处理异常的方式(以及 [=19 的单元测试=]) 会保持不变吗?预先感谢您的帮助。
P.S. Github 项目的回购可在此处获得:Playgroud for Kotlin, Spring Data etc..
P.S.2 堆栈跟踪:
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy65.save(Unknown Source)
at ActorValidationTest.test_WhenNameIsNotPresent_ThenExceptionIsThrown(ActorValidationTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 26 more
Caused by: beans.validator.exceptions.EntityValidationException
at beans.aop.validation.ValidationAdvisor.validate(ValidationAdvisor.kt:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
... 37 more
对我来说 EntityValidationException
(我想被抛出)导致 UndeclaredThrowableException
。
EntityValidationException
科特林class代码:
package beans.validator.exceptions
import beans.validator.constraintViolation.ConstraintViolationInfo
class EntityValidationException (val violationInfos: List<ConstraintViolationInfo>) : Exception() {
}
P.S.3 这也没有用:
@Around(EVERY_SAVE_AND_UPDATE_TO_DATABASE)
@Throws(EntityValidationException::class)
fun validate(point: ProceedingJoinPoint): Any /* rest of code*/
P.S.4 也许问题是 @Aspect
是 @Around
Spring 数据存储库?
companion object {
const val EVERY_SAVE_AND_UPDATE_TO_DATABASE = "execution(* beans.repositories.BaseRepository.save(..))"
}
....
@NoRepositoryBean
public interface BaseRepository<ENTITY, IDENTIFIER extends Serializable>
extends JpaRepository<ENTITY, IDENTIFIER>, JpaSpecificationExecutor<ENTITY> {
}
您正在尝试使方法 save()
或您的存储库抛出它未声明的已检查异常。所以即使方面声明它,那也行不通。你需要让你的例外扩展 RuntimeException
.
我在 Kotlin 中写了一个 validation advisor,它在验证失败时抛出 EntityValidationException
:
@Aspect
@Named
class ValidationAdvisor
@Inject constructor(val validator: EntityValidator) {
@Around(EVERY_SAVE_AND_UPDATE_TO_DATABASE)
fun validate(point: ProceedingJoinPoint): Any {
val result: List<ConstraintViolation<Any>> = validator.validate(getEntity(point))
if (isEntityValid(result))
return point.proceed()
throw EntityValidationException(
violationInfos = result as List<ConstraintViolationInfo>
)
}
private fun getEntity(point: ProceedingJoinPoint): Any {
return point.args[0]
}
private fun isEntityValid(result: List<ConstraintViolation<Any>>): Boolean {
return result.isEmpty()
}
companion object {
const val EVERY_SAVE_AND_UPDATE_TO_DATABASE = "execution(* beans.repositories.BaseRepository.save(..))"
}
}
我有一个 JUnit 测试(我在 Kotlin 中编写了一些部分,在 Java 中编写了一些部分,以在现有的私人项目中学习 Kotlin),它检查是否抛出异常:
@Test(expected = EntityValidationException.class)
public void test_WhenNameIsNotPresent_ThenExceptionIsThrown() throws Exception {
repository.save(/* entity to save */);
}
但后来我看到测试失败,因为它抛出 UndeclaredThrowableException instead of EntityValidationException
. Next, I read that Kotlin does not have checked exception. I think not only me have this problem - I am pretty sure that way of handling exceptions with @ControllerAdvice in Spring and Java 当我们决定在生产项目中切换到 Kotlin 时也可能有问题 - 因为它依赖于抛出的 class,并且抛出UndeclaredThrowableException
剥夺了我们这种可能性。有没有办法绕过这种行为,以确保可以切换到 Kotlin 和 old Spring 处理异常的方式(以及 [=19 的单元测试=]) 会保持不变吗?预先感谢您的帮助。
P.S. Github 项目的回购可在此处获得:Playgroud for Kotlin, Spring Data etc..
P.S.2 堆栈跟踪:
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy65.save(Unknown Source)
at ActorValidationTest.test_WhenNameIsNotPresent_ThenExceptionIsThrown(ActorValidationTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 26 more
Caused by: beans.validator.exceptions.EntityValidationException
at beans.aop.validation.ValidationAdvisor.validate(ValidationAdvisor.kt:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
... 37 more
对我来说 EntityValidationException
(我想被抛出)导致 UndeclaredThrowableException
。
EntityValidationException
科特林class代码:
package beans.validator.exceptions
import beans.validator.constraintViolation.ConstraintViolationInfo
class EntityValidationException (val violationInfos: List<ConstraintViolationInfo>) : Exception() {
}
P.S.3 这也没有用:
@Around(EVERY_SAVE_AND_UPDATE_TO_DATABASE)
@Throws(EntityValidationException::class)
fun validate(point: ProceedingJoinPoint): Any /* rest of code*/
P.S.4 也许问题是 @Aspect
是 @Around
Spring 数据存储库?
companion object {
const val EVERY_SAVE_AND_UPDATE_TO_DATABASE = "execution(* beans.repositories.BaseRepository.save(..))"
}
....
@NoRepositoryBean
public interface BaseRepository<ENTITY, IDENTIFIER extends Serializable>
extends JpaRepository<ENTITY, IDENTIFIER>, JpaSpecificationExecutor<ENTITY> {
}
您正在尝试使方法 save()
或您的存储库抛出它未声明的已检查异常。所以即使方面声明它,那也行不通。你需要让你的例外扩展 RuntimeException
.