gpt4 book ai didi

java - 在 Spring Boot 中运行测试时不满足依赖关系

转载 作者:行者123 更新时间:2023-11-30 06:51:39 24 4
gpt4 key购买 nike

我使用 Spring Initializr 生成了一个 Spring Boot Web 应用程序,使用嵌入式 Tomcat + Thymeleaf 模板引擎,并将其打包为可执行 JAR 文件。

使用的技术:

Spring Boot 1.4.2.RELEASE、Spring 4.3.4.RELEASE、Thymeleaf 2.1.5.RELEASE、Tomcat Embed 8.5.6、Maven 3、Java 8

我有这个测试:

    @ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
public class BooksManagerTests {

/**
* The object being tested.
*/
@Autowired
BooksManager booksManager;


@Test
public void testfindDeviceByKey() {
booksManager.findDeviceByKey("C380F");
}
}


@Configuration
public class PersistenceConfig {

@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}


@Bean
public BooksManager booksManager() {
return new BooksManagerImpl();
}

/**
* Creates an in-memory "rewards" database populated
* with test data for fast testing
*/
@Bean
public DataSource dataSource(){
return
(new EmbeddedDatabaseBuilder())
.addScript("classpath:db/H2.schema.sql")
.addScript("classpath:db/H2.data.sql")
.build();
}

}


@Service("booksManager")
public class BooksManagerImpl implements BooksManager {


private DeviceEventRepository deviceEventRepository;

@Autowired
public void setDeviceEventRepository(DeviceEventRepository deviceEventRepository) {
this.deviceEventRepository = deviceEventRepository;
}

@Override
public List<DeviceEvent> getAllDeviceEvents() {
return deviceEventRepository.getAllDeviceEvents();
}
}


@Repository("deviceEventRepository")
public class JdbcDeviceEventRepository implements DeviceEventRepository {

@Autowired
private JdbcTemplate jdbcTemplate;


@Override
public List<DeviceEvent> getAllDeviceEvents() {
String sql = "select * from t_device_event";
return mapDeviceEvents(jdbcTemplate.queryForList(sql));
}

private List<DeviceEvent> mapDeviceEvents(List<Map<String,Object>> deviceEventsMap) {
return null;
}


}

但我在运行测试时遇到此错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'booksManager': Unsatisfied dependency expressed through method 'setDeviceEventRepository' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tdk.repository.DeviceEventRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

最佳答案

解决了将其添加到 PersistenceConfig 类

@Bean 
public DeviceEventRepository deviceEventRepository() {
return new JdbcDeviceEventRepository();
}

关于java - 在 Spring Boot 中运行测试时不满足依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656443/

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