为啥我的 org.springframework.test.web.servlet.MockMvc 框架无法解析控制器的构造函数参数

Posted

技术标签:

【中文标题】为啥我的 org.springframework.test.web.servlet.MockMvc 框架无法解析控制器的构造函数参数【英文标题】:Why my org.springframework.test.web.servlet.MockMvc framework is failing to resolve constructor parameters of a controller为什么我的 org.springframework.test.web.servlet.MockMvc 框架无法解析控制器的构造函数参数 【发布时间】:2021-05-25 00:43:45 【问题描述】:

我想为我的 Spring Boot 应用程序创建一个单元测试,但在启动 UserControllerTest 测试之一时收到以下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.sample.order.OrderController required a bean of type 'com.sample.order.OrderRepository' that could not be found.


Action:

Consider defining a bean of type 'com.sample.order.OrderRepository' in your configuration.

当我尝试从 UserControllerTest 运行测试时,OrderController 无法满足构造函数参数,反之亦然。

该应用程序很简单,只有两个控制器,用于管理订单和用户。源代码结构如下:

src/
├── main
│   ├── kotlin
│   │   └── com
│   │       └── sample
│   │           ├── OrderApplication.kt
│   │           ├── order
│   │           │   ├── Order.kt
│   │           │   ├── OrderAssembler.kt
│   │           │   ├── OrderController.kt
│   │           │   └── OrderRepository.kt
│   │           └── user
│   │               ├── User.kt
│   │               ├── UserAssembler.kt
│   │               ├── UserController.kt
│   │               └── UserRepository.kt
│   └── resources
│       └── application.properties
└── test
    └── kotlin
        └── com
            └── sample
                ├── order
                │   └── OrderControllerTest.kt
                └── user
                    └── UserControllerTest.kt

一般来说,为了构建我的应用程序,我尝试关注 the Spring Boot kotlin tutorial。

应用程序本身运行没有任何问题。问题出在运行测试时。

我看到框架提出的动作很明显:

考虑在您的配置中定义一个“com.sample.order.OrderRepository”类型的 bean。

,但是我为什么要在配置中定义一个 'com.sample.order.OrderRepository' 类型的 bean?当应用程序本身可以运行并且不需要任何配置时,测试不应该开箱即用吗? 除此之外,OrderRepository 是接口类型:

interface OrderRepository: CrudRepository<Order, Long>

当 Spring 发挥作用时,我不想提供它的实例化。

我尝试了什么:

1。更改控制器的构造函数以接受可为空的参数,例如:

发件人:

class OrderController(private val repository: OrderRepository
              ,private val assembler: OrderAssembler) 
...

收件人:

class OrderController(private val repository: OrderRepository? = null
              ,private val assembler: OrderAssembler? = null) 
...

它解决了这个问题,但出于明显的原因我不想有这个解决方案。

2。将“订单”模拟变量添加到“用户”单元测试

class UserControllerTest(@Autowired val mockMvc: MockMvc) 

    @MockkBean
    private lateinit var userRepository: UserRepository

    @SpykBean
    private lateinit var userAssembler: UserAssembler

    // !!!!!! NOTE: orderRepository inside user tests ¯\_(ツ)_/¯ 
    @MockkBean
    private lateinit var orderRepository: OrderRepository

    // !!!!!! NOTE: orderAssembler inside user tests ¯\_(ツ)_/¯ 
    @SpykBean
    private lateinit var orderAssembler: OrderAssembler
    

    @Test
    fun `Should form expected json response with user data`()
        val user = User(id = 5, login="john.doe@aol.com", firstname = "John", lastname = "Doe")
        every  userRepository.findAll()  returns listOf(user)
        mockMvc.perform(get("/api/v1/users/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk)
    

它也解决了这个问题,但它是一种丑陋的解决方法。

3。在 ComponentScan 中设置显式包名

@SpringBootApplication
@ComponentScan("com.sample.order")
class OrderApplication

fun main(args: Array<String>) 
    runApplication<OrderApplication>(*args)

这并不能解决问题。

UserController的代码:

@RestController
class UserController(private val repository: UserRepository,
                     private val assembler: UserAssembler) 

    @GetMapping("/api/v1/user/id")
    fun findOne(@PathVariable id: Long): EntityModel<User> 
        val user = repository.findById(id)
        if (user.isPresent) 
            return assembler.toModel(user.get())
        
        throw ResponseStatusException(HttpStatus.NOT_FOUND, "This user does not exist")
    

    @GetMapping("/api/v1/users")
    fun all(): CollectionModel<EntityModel<User>> 
        val users = repository.findAll().map 
            assembler.toModel(it)
        
        return CollectionModel.of(users,  //
                linkTo<UserController>all().withRel("all"))
    

它没有帮助。除此之外,我的应用程序可以毫无问题地运行,所以我认为组件扫描不是原因。

使用的版本:

Java:14 科特林:1.4.0 Spring Boot:2.4.1 springmockk:1.1.3 模拟:1.10.5

下面是完整的调用栈:

Failed to resolve parameter [org.springframework.test.web.servlet.MockMvc mockMvc] in constructor [public com.sample.user.UserControllerTest(org.springframework.test.web.servlet.MockMvc)]
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [org.springframework.test.web.servlet.MockMvc mockMvc] in constructor [public com.sample.user.UserControllerTest(org.springframework.test.web.servlet.MockMvc)]
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:221)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:174)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:135)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:61)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestClassConstructor(ClassTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:289)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:281)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:269)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.junit.jupiter.SpringExtension.getApplicationContext(SpringExtension.java:271)
    at org.springframework.test.context.junit.jupiter.SpringExtension.resolveParameter(SpringExtension.java:257)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:207)
    ... 74 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController' defined in file [.../webapp/build/classes/kotlin/main/com/sample/order/OrderController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sample.order.OrderRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1206)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:326)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:122)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 78 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sample.order.OrderRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1777)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1333)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
    ... 97 more

测试源代码:

    OrderControllerTest.kt
package com.sample.order

import com.ninjasquad.springmockk.MockkBean
import com.ninjasquad.springmockk.SpykBean
import io.mockk.every
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import java.util.*

@WebMvcTest
class OrderControllerTest(@Autowired val mockMvc: MockMvc) 

    //Why we need that to have test compilable ?
    /*
    @MockkBean
    private lateinit var userRepository: UserRepository

    @SpykBean
    private lateinit var userAssembler: UserAssembler
    */

    @MockkBean
    private lateinit var orderRepository: OrderRepository

    @SpykBean
    private lateinit var orderAssembler: OrderAssembler

    @Test
    fun `Should form expected json response with order data`()
        val order = Order(id = 7, date = 1501212321)
        every  orderRepository.findById(any())  returns Optional.of(order)
        mockMvc.perform(get("/api/v1/order/7").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk)
                .andExpect(jsonPath("$.id").value(order.id))
    

    UserControllerTest.kt
package com.sample.user

import com.ninjasquad.springmockk.MockkBean
import com.ninjasquad.springmockk.SpykBean
import io.mockk.every
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

@WebMvcTest
class UserControllerTest(@Autowired val mockMvc: MockMvc) 

    @MockkBean
    private lateinit var userRepository: UserRepository

    @SpykBean
    private lateinit var userAssembler: UserAssembler

    /*
    @MockkBean
    private lateinit var orderRepository: OrderRepository

    @SpykBean
    private lateinit var orderAssembler: OrderAssembler
    */

    @Test
    fun `Should form expected json response with user data`()
        val user = User(id = 5, login = "john.doe@aol.com", firstname = "John", lastname = "Doe")
        every  userRepository.findAll()  returns listOf(user)
        mockMvc.perform(get("/api/v1/users").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk)
    

源代码可在github获取

【问题讨论】:

你能分享你测试的完整代码吗?看起来您可能正在使用@WebMvcTest,它将专注于您的应用程序的 WebMVC bean,过滤掉 JPA 存储库等。 您找到解决方案了吗? @pollux552 是的,我做到了。答案中的解决方案。 【参考方案1】:

解决办法是改变测试注解

添加@AutoConfigureMockMvc 添加@SpringBootTest 删除@WebMvcTest

工作测试注释如下所示:

@AutoConfigureMockMvc
@SpringBootTest
//@WebMvcTest
class UserControllerTest(@Autowired val mockMvc: MockMvc) 
    ...

@AutoConfigureMockMvc - 启用和配置 MockMvc 的自动配置

@SpringBootTest - 告诉 Spring Boot 去寻找一个主配置类(例如一个带有 @SpringBootApplication 的配置类),并使用它来启动一个 Spring 应用程序上下文。 SpringBootTest 加载完整的应用程序并注入所有可能很慢的 bean。

@WebMvcTest - 用于测试控制器层,您需要提供使用 Mock Objects 所需的剩余依赖项。

更多细节可以在这里找到:

other *** question mkyong.com tutorial

【讨论】:

以上是关于为啥我的 org.springframework.test.web.servlet.MockMvc 框架无法解析控制器的构造函数参数的主要内容,如果未能解决你的问题,请参考以下文章

为啥在尝试对整个 Spring Batch Job 进行单元测试时出现此错误?没有可用的“org.springframework.batch.core.Job”类型的合格bean

为啥我tomcat已启动就报错了 org.apache.catalina.LifecycleException: Failed to start component

org.springframework.beans.NotWritablePropertyException:无效的属性

使用我的第一个 Maven Spring Project 获取 org.springframework.beans.factory.BeanCreationException

Feign调用异常org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET&#(代

未能执行目标 org.springframework