복붙노트

[SPRING] Spring Boot @WebMvcTest를 사용하여 테스트 할 때 내 컨텍스트에서 다른 @Controller를 제외하는 방법

SPRING

Spring Boot @WebMvcTest를 사용하여 테스트 할 때 내 컨텍스트에서 다른 @Controller를 제외하는 방법

나는 여러 개의 컨트롤러를 가지고 있는데, @WebMvcTest에 하나의 컨트롤러를 지정하면 다른 컨트롤러가 컨텍스트에로드되지 않는다는 것을 이해할 수 있습니다. 문서에서

내 첫 번째 컨트롤러

@Controller
public class MyController {

    @Autowired
    private MyService myService;

    private final Logger logger = Logger.getLogger(this.getClass());

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> index() {
        try {
            myService.get();
            return new ResponseEntity<String>(HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
        return new ResponseEntity<String>("REQUEST FAILED", HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

내 다른 컨트롤러

@Controller
public class MyOtherController {

    @Autowired
    private MyOtherService myOtherService;

    etc...
}

내 컨트롤러 테스트

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = { MyController.class }, secure = false)
@ActiveProfiles({ "test" })
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    MyService myService;

    @Test
    public void testBaseReq() throws Exception {
        Testing dummyData = new Testing();
        dummyData.setData("testing");
        when(myService.get(anyInt())).thenReturn(dummyData);

        this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk());
    }
}

하지만이 테스트를 실행하면 컨텍스트를로드 할 때 MyOtherContoller에서 Bean MyOtherService를로드하는 데 실패합니다.

2017-09-28 11:50:11.687 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'myOtherController'
2017-09-28 11:50:11.687 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating instance of bean 'myOtherController'
2017-09-28 11:50:11.687 DEBUG 16552 --- [           main] o.s.b.f.annotation.InjectionMetadata     : Registered injected element on class [my.package.other.myOtherController]: AutowiredFieldElement for private my.package.other.myOtherService my.package.other.myOtherController.myOtherService
2017-09-28 11:50:11.687 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Eagerly caching bean 'myOtherController' to allow for resolving potential circular references
2017-09-28 11:50:11.687 DEBUG 16552 --- [           main] o.s.b.f.annotation.InjectionMetadata     : Processing injected element of bean 'myOtherController': AutowiredFieldElement for private my.package.other.myOtherService my.package.other.myOtherController.myOtherService
2017-09-28 11:50:11.688 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'myOtherService'
2017-09-28 11:50:11.688 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating instance of bean 'myOtherService'
2017-09-28 11:50:11.689 DEBUG 16552 --- [           main] o.s.b.f.annotation.InjectionMetadata     : Registered injected element on class [my.package.other.myOtherService]: AutowiredFieldElement for private my.package.other.myOtherMapper my.package.other.myOtherService.myOtherMapper
2017-09-28 11:50:11.689 DEBUG 16552 --- [           main] o.s.b.f.annotation.InjectionMetadata     : Registered injected element on class [my.package.other.myOtherService]: AutowiredFieldElement for private ie.aib.services.coredemo.FinancialsRegionService my.package.other.myOtherService.financialsRegionService
2017-09-28 11:50:11.689 DEBUG 16552 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Eagerly caching bean 'myOtherService' to allow for resolving potential circular references
2017-09-28 11:50:11.689 DEBUG 16552 --- [           main] o.s.b.f.annotation.InjectionMetadata     : Processing injected element of bean 'myOtherService': AutowiredFieldElement for private my.package.other.myOtherMapper my.package.other.myOtherService.myOtherMapper
2017-09-28 11:50:11.690  WARN 16552 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myOtherController': Unsatisfied dependency expressed through field 'myOtherService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myOtherService': Unsatisfied dependency expressed through field 'myOtherMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'my.package.other.myOtherMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

WebMvcTest 주석에서 테스트 할 컨트롤러를 지정하는 것이 컨트롤러를로드하는 데만 제한된다는 생각이 들었습니다. 그러나 다른 컨트롤러를로드하려고 시도하고 빈이 조롱되지 않기 때문에 실패합니다.

나는 무엇을 놓치고 있는지 또는 내 이해가 틀린가? 나는 테스트중인 Controller를 위해 콩만을 모방해야한다고 생각한다. 또한 excludeFilter를 사용하여 다른 컨트롤러의 패키지를 제외 시키려고했지만 오류가 변경되지 않았습니다.

해결법

  1. ==============================

    1.테스트에 사용 된 Application.class가 @ComponentScan 주석을 포함하지 않는지 확인하십시오. 예를 들어, 이것은 귀하의 패키지 구조입니다.

    테스트에 사용 된 Application.class가 @ComponentScan 주석을 포함하지 않는지 확인하십시오. 예를 들어, 이것은 귀하의 패키지 구조입니다.

    abc-project
      +--pom.xml
      +--src
        +-- main
          +-- com
            +-- abc
              +-- Application.java
              +-- controller
                +-- MyController.java
        +-- test
          +-- com
            +-- abc
              +-- Application.java
              +-- controller
                +-- MyControllerTest.java
    

    테스트중인 Application.java는이 예제와 비슷하게 보일 것입니다.

    @SpringBootApplication
    public class Application {
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class, args);
        }
    }
    
  2. ==============================

    2.my.package.other.myOtherMapper (아마도 Mybatis Mapper 파일)가 없거나 명확하게 초기화되지 않았습니다.

    my.package.other.myOtherMapper (아마도 Mybatis Mapper 파일)가 없거나 명확하게 초기화되지 않았습니다.

    myOtherService 구현 클래스는 제대로 매핑되지 않은 Mapper 파일을 가지고 있습니다.

    먼저지도에 표시해야 할 수 있습니다. 가능한 경우 Mapper XML 내용을 게시 할 수 있습니다.

      <context:component-scan base-package="org.example">       
        <context:exclude-filter type="custom" expression="abc.xyz.MyOtherController"/>
      </context:component-scan>
    
  3. from https://stackoverflow.com/questions/46460131/how-to-exclude-other-controller-from-my-context-when-testing-using-spring-boot by cc-by-sa and MIT license