SpringBootTest:没有可用的类型为'org.springframework.test.web.servlet.MockMvc'的合格bean。

40

嘿,我开始学习使用Spring Boot Test框架进行Spring Boot JUnit测试。在创建测试用例时,我遇到了以下问题。

Hey,我开始学习使用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]

我知道MockMvc名称的bean在spring-boot中找不到,但为什么找不到它,以及我如何做才能使应用程序正常工作。


你是使用嵌入式Tomcat还是外部Tomcat实例与Servlet初始化器? - Karthik R
嵌入式Tomcat: D:\mavenrepo\org\springframework\boot\spring-boot-starter-tomcat\1.5.3.RELEASE\spring-boot-starter-tomcat-1.5.3.RELEASE.jar D:\mavenrepo\org\apache\tomcat\embed\tomcat-embed-core\8.5.14\tomcat-embed-core-8.5.14.jar D:\mavenrepo\org\apache\tomcat\embed\tomcat-embed-el\8.5.14\tomcat-embed-el-8.5.14.jar D:\mavenrepo\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.14\tomcat-embed-websocket-8.5.14.jar - Prabhat Yadav
5个回答

43

希望您已经使用了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();
  }

2
使用此代码会出现org.springframework.beans.factory.UnsatisfiedDependencyException异常:创建bean时出错,bean名称为'com.hanselnpetal.ApplicationTest',字段'webApplicationContext'的依赖项无法满足;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有符合条件的类型为'org.springframework.web.context.WebApplicationContext'的bean可用:至少需要1个bean作为自动装配候选项。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}。 - Prabhat Yadav
1
你的依赖有问题吗?你有spring-boot-starter-web吧?这对我来说很好用。 - Karthik R
4
使用spring-boot-starter-web的依赖解决了我的问题。 - trevorsky
尝试过了,现在我得到了一个不同的错误:java.lang.Exception:没有可运行的方法 - djangofan
与版本3.x完美兼容,解决了使用Spring框架的Maven依赖问题。 - davidvera
显示剩余3条评论

17

试着向这个类添加以下注释。

import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc

10

我遇到了相同的问题,因为我正在遵循使用WebFlux(响应式Web)而不是同步Web的教程。假设单元测试可以是同步的,最后这个方法对我有用(在Gradle中)

implementation 'org.springframework.boot:spring-boot-starter-webflux'
// Required for MockMvc autoconfigure
testImplementation 'org.springframework.boot:spring-boot-starter-web'

对我有用!我正在使用WebFlux,现在可以工作了。 - Jhonatan S. Souza

3
我也曾遇到同样的问题,因为我忘记从test文件夹中的application.properties文件中删除以下行:

spring.main.web-application-type=none

只需将其删除即可解决问题。


2

我相信@karthik-r的答案是正确的!

我之前也遇到过同样的问题,所以有一件事情可以帮助“调试”Spring注入的内容。

@BeforeEach
void printApplicationContext() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    //This  
    Arrays.stream(webApplicationContext.getBeanDefinitionNames())
            .map(name -> webApplicationContext.getBean(name).getClass().getName())
            .sorted()
            .forEach(System.out::println);
}

当然,如果你有

@Autowired
private WebApplicationContext webApplicationContext;

这将打印所有Spring注入的bean。 最后还有一件事情,如果您正在使用JUnit 5,则必须修改的是:
将@RunWith更改为
@ExtendWith(SpringExtension.class)

就是这样...

=)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接