#spring-boot #kotlin #spring-boot-test #mockmvc
#весенняя загрузка #kotlin #spring-boot-test #mockmvc
Вопрос:
Файл сборки
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.3.3.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
id("com.google.cloud.tools.jib") version "2.5.0"
kotlin("jvm") version "1.4.0"
kotlin("plugin.spring") version "1.4.0"
kotlin("plugin.jpa") version "1.4.0"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-data-rest")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-activemq")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.flywaydb:flyway-core")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
testImplementation("com.h2database:h2:1.4.200")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "14"
}
}
Контроллер
@RestController
@RequestMapping("/notification")
class NotificationResource(
private val jobService: JobService
) {
@PostMapping("/enqueue-mobile", produces = [APPLICATION_JSON_VALUE], consumes = [APPLICATION_JSON_VALUE])
@ResponseStatus(ACCEPTED)
fun enqueueMobile(@Valid @RequestBody mobile: Mobile): List<Job> = jobService.create(mobile)
@GetMapping("/job-status/{id}", produces = [APPLICATION_JSON_VALUE])
@ResponseStatus(OK)
fun jobStatus(@Valid @PathVariable id: UUID): Job = jobService.fetch(id).get()
}
data class Mobile(
val ids: List<Long>,
val message: String
)
Файл модульного тестирования
@SpringBootTest
@ActiveProfiles("test")
@AutoConfigureMockMvc
class NotificationResourceMobileTests {
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `with correct payload having one mobile id in a list and message - request returns http ok and response`() {
val mobile = Mobile(ids = listOf<Long>(100, 101, 102), message = "test")
mockMvc.perform(post(urlPath).contentType(APPLICATION_JSON_VALUE).content(mobile.asJsonString()))
.andDo(print())
.andExpect(status().isAccepted)
}
companion object {
const val urlPath = "/notification/enqueue-mobile"
}
}
Просьба
MockHttpServletRequest:
HTTP Method = POST
Request URI = /notification/enqueue-mobile
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"38"]
Body = {"ids":[100,101,102],"message":"test"}
Session Attrs = {}
Handler:
Type = com.notification.resource.NotificationResource
Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.util.NestedServletException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"timestamp":"2020-09-04T23:51:49.609645","status":400,"error":"Bad Request","message":"'java.util.List com.notification.resource.Mobile.getIds()'","trace":"java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'ntat com.notification.service.JobService$create$1.invoke(JobService.kt:29)ntat com.notification.service.JobService$create$1.invoke(JobService.kt:19)ntat com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)ntat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)ntat java.base/java.lang.reflect.Method.invoke(Method.java:564)ntat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)ntat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)ntat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)ntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)ntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)ntat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)ntat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)ntat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)ntat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)ntat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)ntat javax.servlet.http.HttpServlet.service(HttpServlet.java:652)ntat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)ntat org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)ntat javax.servlet.http.HttpServlet.service(HttpServlet.java:733)ntat org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)ntat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)ntat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)ntat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)ntat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)ntat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)ntat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)ntat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)ntat org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183)ntat com.notification.resource.NotificationResourceMobileTests.with correct payload having one mobile id in a list and message - request returns http ok and response(NotificationResourceMobileTests.kt:134)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)ntat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)ntat java.base/java.lang.reflect.Method.invoke(Method.java:564)ntat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)ntat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)ntat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)ntat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)ntat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)ntat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)ntat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)ntat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)ntat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)ntat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)ntat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)ntat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)ntat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)ntat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)ntat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)ntat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)ntat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)ntat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)ntat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)ntat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)ntat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)ntat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)ntat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)ntat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)ntat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)ntat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)ntat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)ntat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)ntat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)ntat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)ntat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)ntat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)ntat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)ntat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)ntat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)ntat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)ntat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)ntat org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)ntat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)ntat java.base/java.lang.reflect.Method.invoke(Method.java:564)ntat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)ntat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)ntat org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)ntat org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)ntat com.sun.proxy.$Proxy2.stop(Unknown Source)ntat org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)ntat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)ntat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)ntat java.base/java.lang.reflect.Method.invoke(Method.java:564)ntat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)ntat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)ntat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)ntat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)ntat org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)ntat org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)ntat org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)ntat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)ntat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)ntat org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)ntat java.base/java.lang.Thread.run(Thread.java:832)n","path":"uri=/notification/enqueue-mobile"}
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /notification/enqueue-mobile
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"38"]
Body = {"ids":[100,101,102],"message":"test"}
Session Attrs = {}
Handler:
Type = com.notification.resource.NotificationResource
Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.util.NestedServletException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"timestamp":"2020-09-04T23:51:49.609645","status":400,"error":"Bad Request","message":"'java.util.List com.notification.resource.Mobile.getIds()'","path":"uri=/notification/enqueue-mobile"}
Forwarded URL = null
Redirected URL = null
Cookies = []
Status expected:<202> but was:<400>
Expected :202
Actual :400
Почему я получаю NoSuchMethodError — когда у меня есть поле в
data class
. Примечание: Я могу протестировать функцию после запуска приложения и использования Postman. То же самое не удается при модульном тестировании.
Модульное тестирование сmockmvc
работает не так, как ожидалось. То же самое отлично работает дляget
методов. Есть какие-либо входные данные?
java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'
at com.notification.service.JobService$create$1.invoke(JobService.kt:29)
at com.notification.service.JobService$create$1.invoke(JobService.kt:19)
at com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Комментарии:
1. Вы можете увидеть полную трассировку ошибок здесь. gist.github.com/gpuliyar/3b700dafe6947deb081ece5b4d8cc028
2. Показать
JobService.create
.3. @AbhijitSarkar — вот как
jobservice.create
выглядит — gist.github.com/gpuliyar/e2eab7896e6259f6ec236992b1736f0c4. Не бери в голову. Исправлена проблема. Переместил класс данных в отдельный пакет. Странно, что функциональность просто отлично работала при тестировании с использованием postman, когда класс данных находился в том же файле, что и ресурс контроллера, но модульные тесты завершились неудачей.