@WebMvcTest测试类中的NoSuchBeanDefinitionException

时间:2018-11-13 09:23:35

标签: java spring spring-mvc spring-boot

我想在BookRestController中测试我的其余端点。我用@WebMvcTest编写了一个测试。

@RunWith(SpringRunner.class)
@WebMvcTest(BookRestController.class)
public class BookRestControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private CategoryService categoryService;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void should_create_new_category_when_try_to_update() throws Exception {

        given(categoryService.getCategoryById(20L)).willReturn(null);
        Category category = new Category("Fantastyka");

        ResultActions resultActions = mockMvc.perform(put("/api/category/10")
        .contentType(MediaType.APPLICATION_JSON)
        .content(objectMapper.writeValueAsString(category)));

        resultActions.andExpect(status().isNoContent());

    }
}

在存储库软件包中,我有4个存储库,但在测试端点中,我仅使用其中一个。 enter image description here

这是我来自BookRestController

的方法
@RestController
public class BookRestController {

    @Autowired
    private CategoryService categoryService;

  @RequestMapping(value = "/api/category/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Category> updateCategory(@PathVariable Long id, @RequestBody Category category){

        return ResponseEntity
                .status(HttpStatus.NO_CONTENT)
                .body(categoryService.updateCategory(id, category));
    }
}

现在,当我进行测试时,我得到一个错误

  

原因:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名称为'demoApplication'的bean时出错:不满意   通过构造函数参数0表示的依赖关系;嵌套异常   是org.springframework.beans.factory.NoSuchBeanDefinitionException:否   类型的合格豆   提供“ com.sda.spring.demo.repository.BookRepository”:预计在   至少1个符合自动装配候选条件的bean。相依性   注释:{}

为什么?我在测试中没有使用BookRepository。我该如何解决?

完整日志:

  

java.lang.IllegalStateException:无法加载ApplicationContext

     在

  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)     在   org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)     在   org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:99)     在   org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)     在   org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)     在   org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner $ 1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)     在   org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)     在org.junit.runners.ParentRunner处$ 3.run(ParentRunner.java:290)在   org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)在   org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)在   org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)在   org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)在   org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)     在   org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)     在org.junit.runners.ParentRunner.run(ParentRunner.java:363)处   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)     在org.junit.runner.JUnitCore.run(JUnitCore.java:137)处   com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)     在   com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)     在   com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)     在   com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)   造成原因:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名称为'demoApplication'的bean时出错:不满意   通过构造函数参数0表示的依赖关系;嵌套异常   是org.springframework.beans.factory.NoSuchBeanDefinitionException:否   类型的合格豆   提供“ com.sda.spring.demo.repository.BookRepository”:预计在   至少1个符合自动装配候选条件的bean。相依性   注释:{},位于   org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:767)     在   org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1308)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1154)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)     在   org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:320)     在   org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)     在   org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)     在   org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)     在   org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)     在   org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)     在   org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)     在   org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)     在   org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)     在   org.springframework.boot.SpringApplication.run(SpringApplication.java:316)     在   org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)     在   org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)     在   org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)     ... 25更多原因:   org.springframework.beans.factory.NoSuchBeanDefinitionException:否   类型的合格豆   提供“ com.sda.spring.demo.repository.BookRepository”:预计在   至少1个符合自动装配候选条件的bean。相依性   注释:{},位于   org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1646)     在   org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205)     在   org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)     在   org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855)     在   org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758)     ...还有43

Spring Boot:v2.1.0.RELEASE

编辑: 有用。我想念@Autowire中的BookRepository DemoApplication ... 我删除了此代码,现在可以使用

@Autowired
    private ApplicationContext applicationContext;

    private BookRepository bookRepository;

    private CategoryRepository categoryRepository;

    @Autowired
    public DemoApplication(BookRepository bookRepository, CategoryRepository categoryRepository) {
        this.bookRepository = bookRepository;
        this.categoryRepository = categoryRepository;
    }

1 个答案:

答案 0 :(得分:0)

您的主应用程序类将加载定义的任何bean或通过注释启用的功能。

例如@EnableSchedling@ComponentScan@Import

在切片测试中将全部加载。

有关详细信息,请参阅此文档,

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-user-configuration

  

如果您以合理的方式构造代码,则默认情况下,将@SpringBootApplication类用作测试的配置。

     

然后变得重要的是,不要使用特定于应用程序功能特定区域的配置设置来丢弃应用程序的主类。