gpt4 book ai didi

java - UnsatisfiedDependencyException 在 SpringBoot 中使用 @DataJpaTest

转载 作者:行者123 更新时间:2023-11-30 07:56:15 26 4
gpt4 key购买 nike

我正在使用 SpringBoot 并且我有一个 DataJpaTest,但是当我运行测试类时,我得到这个 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)

我认为发生这种情况是因为我的 Application 类中有一个 RestTemplate 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();
}
}

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

最佳答案

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

但是我发现了 2 种方法来改变我的测试以使我的 DataJpaTest 运行,但不确定哪个是最好的:

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

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

@MockBean
private RestTemplate restTemplate;

方法二 - 添加 AutoConfigureWebClient 注释,以便 spring 连接 RestTemplateBuilder

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

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

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

关于java - UnsatisfiedDependencyException 在 SpringBoot 中使用 @DataJpaTest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com