![](/img/trans.png)
[英]NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.web.reactive.error.ErrorAttributes' available:
[英]SpringBootTest : No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available:
嘿,在创建测试用例时,我已经开始使用 spring boot 测试框架学习 spring-boot junit 测试,我面临以下问题。
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
在上面的代码中,我收到错误
Caused by: **org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}**
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
我知道 spring-boot 没有找到 MockMvc 名称 bean,但为什么它无法找到它,以及我如何才能使应用程序正常工作。
希望你有spring-boot-starter-web
依赖。 不确定您使用的是哪个版本的 Spring boot,而是以这种方式构建 mockMvc?
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
我遇到了同样的问题,因为我正在学习使用 WebFlux(反应式 Web)而不是同步 Web 的教程。 假设单元测试可以是同步的,最后这对我有用(在 Gradle 中)
implementation 'org.springframework.boot:spring-boot-starter-webflux'
// Required for MockMvc autoconfigure
testImplementation 'org.springframework.boot:spring-boot-starter-web'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.