programing

스프링 부트테스트 : 'org.springframework.test.web.servlet' 유형의 정규 빈이 없습니다.MockMvc' 사용 가능:

newnotes 2023. 3. 1. 11:30
반응형

스프링 부트테스트 : 'org.springframework.test.web.servlet' 유형의 정규 빈이 없습니다.MockMvc' 사용 가능:

아래 문제에 직면한 테스트 케이스를 작성할 때 스프링 부트 테스트 프레임워크를 사용하여 스프링 부트 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 name bean은 spring-boot에서 찾을 수 없지만 왜 찾을 수 없는지, 어플리케이션이 정상적으로 동작하도록 어떻게 할 수 있는지 알고 있습니다.

가지고 계셨기를 바랍니다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();
  }

다음 주석을 클래스에 추가해 보십시오.

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

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

동기 웹이 아닌 WebFlux(리액티브 웹)를 사용한 튜토리얼을 따르고 있기 때문에 같은 문제가 있었습니다.유닛 테스트를 동기화할 수 있다고 가정하면, 드디어 (그래들에서는) 이 테스트가 성공했습니다.

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

저도 같은 문제가 있었습니다. 왜냐하면 다음 행을 삭제하는 것을 잊어버렸기 때문입니다.application.properties줄서다test폴더:

spring.main.web-application-type=none

그것을 제거하는 것만으로 문제가 해결되었다.

@karthik-r의 답변이 맞다고 생각합니다!

저도 같은 문제가 있어서 스프링이 주입한 비잉을 디버깅하는 데 도움이 되는 게 그거였어요.

@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;

이것은 봄철 주입된 콩을 모두 인쇄할 것이다.마지막으로 JUnit 5를 사용하는지 수정해야 할 것이 하나 더 있습니다.

@RunWith를 로 변경합니다.

@ExtendWith(SpringExtension.class)

그게 다야...

=)

언급URL : https://stackoverflow.com/questions/51299015/springboottest-no-qualifying-bean-of-type-org-springframework-test-web-servle

반응형