嘿,在创建测试用例时,我已经开始使用spring boot Test框架进行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,但是为什么它找不到它,我怎么做才能使应用程序正常工作。
答案 0 :(得分:1)
希望您具有spring-boot-starter-web
依赖性。不知道您使用的是哪种版本的Spring Boot,而是用这种方式来构建ockMockMvc?
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
答案 1 :(得分:0)
我遇到了同样的问题,因为我正在学习使用WebFlux(反应性Web)而不是同步Web的教程。假设单元测试可以是同步的,那么最终这对我有用(在Gradle中)
implementation 'org.springframework.boot:spring-boot-starter-webflux'
// Required for MockMvc autoconfigure
testImplementation 'org.springframework.boot:spring-boot-starter-web'