在SpringBoot中使用@DataJpaTest时出现不满意的依赖异常

时间:2017-02-23 12:03:32

标签: java spring unit-testing spring-boot resttemplate

我正在使用SpringBoot而且我有一个DataJpaTest,但是当我运行Test类时,我得到了这个StackTrace:

 java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'restTemplate' defined in br.com.mobtrack.api.MobTrackApplication: Unsatisfied dependency expressed through method 'restTemplate' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 28 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)

我认为这是因为我的RestTemplate类中有一个Application bean,如下所示:

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

这是我的测试类:

@RunWith(SpringRunner.class)
@DataJpaTest
public class CityRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private CityRepository cityRepository;

    private City city;

    @Before
    public void init() {
        city = new City();
        city.setName("New York");
        city.setImage("http://www.mockimage.com");
    }

    @Test
    public void findByNameShouldReturnCity() throws Exception {
        this.entityManager.persist(city);
        Optional<City> hasCity = this.cityRepository.findByNameIgnoreCase("New York");
        city = hasCity.get();
        assertThat(city.getId()).isNotNull();
        assertThat(city.getName()).isEqualTo("New York");
        assertThat(city.getImage()).isEqualTo("http://www.mockimage.com");
    }

    @Test
    public void findByNameStartingWithShouldReturnCity() throws Exception {
        this.entityManager.persist(city);
        Optional<City> hasCity = this.cityRepository.findByNameStartingWithIgnoreCase("New");
        city = hasCity.get();
        assertThat(city.getId()).isNotNull();
        assertThat(city.getName()).isEqualTo("New York");
        assertThat(city.getImage()).isEqualTo("http://www.mockimage.com");
    }

    @Test
    public void findByNameWhenNoCityShouldReturnFalse() throws Exception {
        this.entityManager.persist(city);
        Optional<City> hasCity = this.cityRepository.findByNameStartingWithIgnoreCase("Ohaio");
        assertThat(hasCity.isPresent()).isFalse();
    }
}

欢迎任何帮助,非常感谢!

2 个答案:

答案 0 :(得分:2)

正如错误清楚地说 - 没有类型RestTemplateBuilder的限定bean可用于RestTemplate bean构建。

RestTempalteBuilder的bean由用于web的spring boot starter注入上下文。通常不需要将RestTemplateBuilder bean声明为上下文,因为它已由spring-boot自动配置提供。如果项目是一个弹簧启动应用程序,这将按预期开箱即用。

如果需要,可以通过在应用程序配置中创建一个新的来自定义它。如下所示:

@Bean
public RestTemplateBuilder restTemplateBuilder() {
    return new RestTemplateBuilder()
            .basicAuthorization("abc", "password");
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

如果没有真正的理由来自定义它,你宁可为RestTemplate提供一个更简单的bean定义,如下所示:

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

答案 1 :(得分:0)

我不喜欢其他解决方案,因为我确实希望我的应用程序使用spring提供的RestTemplateBuilder,因为它提供了一些默认的消息转换器和运行我的应用程序时所需的其他功能。

但是,我找到了两种方法来更改测试以运行DataJpaTest,但不确定哪种方法最好:

方法一-在测试中提供一个模拟的RestTemplate。

@RunWith(SpringRunner.class)
@DataJpaTest
public class SomeTest {

    @MockBean
    private RestTemplate restTemplate;

方法二-添加AutoConfigureWebClient批注,以便Spring将连接RestTemplateBuilder

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureWebClient
public class SomeTest {

通过两种方式,我都可以将现有的已配置其余模板保留在应用程序类中:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}