简体   繁体   English

使用Spring Boot @WebMvcTest测试时如何从我的上下文中排除其他@Controller

[英]How to exclude other @Controller from my context when testing using Spring Boot @WebMvcTest

I have multiple controllers and my understanding is that by specifying one controller in @WebMvcTest that other controllers wouldn't be loaded into context. 我有多个控制器,我的理解是,通过在@WebMvcTest中指定一个控制器,其他控制器将不会加载到上下文中。 From the docs 来自文档

controllers - Specifies the controllers to test. controllers-指定要测试的控制器。 May be left blank if all @Controller beans should be added to the application context. 如果所有@Controller bean应该添加到应用程序上下文中,则可以留空。

My first Controller 我的第一个控制器

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

}

My other controller 我的其他控制器

@Controller
public class MyOtherController {

    @Autowired
    private MyOtherService myOtherService;

    etc...
}

My Test for my Controller 我对控制器的测试

@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());
    }
}

But when I run this test, it fails trying to load the bean MyOtherService from MyOtherContoller when loading the context. 但是,当我运行此测试时,在加载上下文时尝试从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)}

I thought specifying the controller to test in the WebMvcTest annotation would limit it to the only loading that contoller. 我认为在WebMvcTest批注中指定要测试的控制器会将其限制为只能加载该contoller。 But its trying to load the other controller and because its beans aren't mocked it fails. 但是它试图加载另一个控制器,并且因为没有嘲笑它的bean,所以它失败了。

What am I missing or is my understanding incorrect? 我缺少什么或者我的理解不正确? I think I should only have to mock beans for the Controller under test. 我认为我只需要为测试中的Controller模拟bean。 I've also tried an excludeFilter to specifically exclude the package for the other Controller but that didn't change the error. 我还尝试了excludeFilter专门排除其他Controller的程序包,但这并没有改变错误。

Please make sure the Application.class your test picks up, doesn't contain @ComponentScan annotation. 请确保您的测试中的Application.class不包含@ComponentScan批注。 For example, this is your package structure 例如,这是您的包装结构

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

The Application.java under test should look similar to this example, 测试Application.java应该看起来类似于此示例,

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

my.package.other.myOtherMapper (probably Mybatis Mapper file) is missing or not clearly initialized. my.package.other.myOtherMapper(可能是Mybatis Mapper文件)丢失或未明确初始化。

As of my understanding, myOtherService implementation class has Mapper file which is not mapped properly. 据我了解,myOtherService实现类具有未正确映射的Mapper文件。

You may have to map them first. 您可能必须先将它们映射。 You can post the Mapper xml content if possible. 如果可能,您可以发布Mapper xml内容。

  <context:component-scan base-package="org.example">       
    <context:exclude-filter type="custom" expression="abc.xyz.MyOtherController"/>
  </context:component-scan>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用于Controller的Spring Boot Testing @WebMvcTest似乎在上下文中加载其他控制器 - Spring Boot Testing @WebMvcTest for a Controller appears to load other controllers in the context 将@WebMvcTest 与spring-boot 一起使用时如何排除@Configuration 类? - How to exclude a @Configuration class when using @WebMvcTest with spring-boot? 如何使用@WebMvcTest从上下文中排除包 - How to exclude packages from a context using @WebMvcTest Spring MVC - 使用 @WebMvcTest 测试控制器时 @EnableGlobalMethodSecurity 出现错误 404 - Spring MVC - Error 404 with @EnableGlobalMethodSecurity when testing Controller using @WebMvcTest 如何在 Spring Boot WebMvcTest 中设置上下文路径 - How to set the context path in Spring Boot WebMvcTest 在 Spring Boot 测试类上使用 @WebMvcTest 注释时出错 - Error when using @WebMvcTest annotation on a Spring Boot test class 从SpringBoot WebMvcTest或其他应用程序上下文中扫描WebMvcTest排除PropertySource - Excluding PropertySource from scanning in SpringBoot WebMvcTest or other application context for WebMvcTest 使用Spock Testing Framework和Spring Boot来测试我的REST控制器 - Using Spock Testing Framework with Spring Boot to test my REST Controller Spring-Boot WebMvcTest:如何使用身份验证 object 参数测试 controller 方法? - Spring-Boot WebMvcTest: How to test controller method with Authentication object parameter? 在 Spring Boot 中,如何在 @WebMvcTest 期间从启动器启用 @ControllerAdvice - In Spring Boot, how do I enable a @ControllerAdvice from a starter during a @WebMvcTest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM