使用 @WebMvcTest 进行测试时出现 ApplicationContext 异常

ApplicationContext Exception in Test with @WebMvcTest

我有一个 Spring 引导应用程序 (1.5.10.RELEASE),其中包含一个主要的 (SpringBootApplication),如下所示:

@SpringBootApplication
@Configuration
@EntityScan(basePackages = { "db.modell", "db.modell.base" })
@ComponentScan(basePackages = { "de.gui.test" })
public class SpringBootConsoleApplication {
   public static void main(String[] args) throws Exception {
    SpringApplication.run(SpringBootConsoleApplication.class, args);
  }
}

和两个如下所示的 REST 控制器:

@RestController
@RequestMapping("/as")
public class AController {
  @Autowired
  private ARepository aRepository;

  @RequestMapping(method = RequestMethod.GET)
  public ResponseEntity<Collection<A>> getAs() {
    return new ResponseEntity<>(orgtFarbeRepository.findAll(), HttpStatus.OK);
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public ResponseEntity<A> getA(@PathVariable long id) {
    A a = ARepository.findOne(id);

    if (party != null) {
      return new ResponseEntity<>(ARepository.findOne(id), HttpStatus.OK);
    } else {
      return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }
  }
}

此外,我有一个这样的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(AController.class)
public class AControllerTest {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private ARepository ARepository;

  @Test
  public void firstTest() throws Exception {
    A a = new aFarbe();
    a.set....
    when(ARepository.findAll()).thenReturn(Collections.singleton(a));
    mvc.perform(
            get("/as")
            .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
    )
      .andExpect(status().isOk());
  }
}

存储库如下所示:

public interface ARepository extends CrudRepository<A, Long>
{
    Collection<A> findAll();
}
public interface BRepository extends CrudRepository<B, Long>
{
  Collection<B> findAll();
}

A 和 B 他们自己是 JPA 注释的 类。整个应用程序包含对数据库的访问..

此外,我有这样的服务:

@Service
public class XService {
  private static final Logger LOGGER = LoggerFactory.getLogger(XService.class);

  @Autowired
  private ARepository aRepository;

  @Autowired
  private BRepository bRepository;
...
}

XService 不通过@Autowire 等使用(只需要删除它):

所以我尝试 运行 AControllerTest 我得到以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) .. .. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XService': Unsatisfied dependency expressed through field 'BRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'BRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} .. .. at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'BRepository' 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:1493) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 44 more

我的假设是在测试期间启动了比应有的更多上下文。问题是我怎样才能防止这种情况发生?这意味着只启动 AControler 的上下文,仅此而已?我认为基于 @WebMvcTest(AController.class) 它应该已经受到限制,看起来事实并非如此......

引用的答案并没有真正回答我的问题,但在上下文中 hint 给了我解决方案。这意味着要将以下内容添加到我的测试中:

所以我必须添加 @OverrideAutoConfiguration(enabled=true):

@RunWith(SpringRunner.class)
@WebMvcTest(OrgtFarbenController.class)
@OverrideAutoConfiguration(enabled=true)
public class AControllerTest {
...
}