我有这个测试类
我使用Spring Initializr生成了一个Spring Boot Web应用程序,使用嵌入式Tomcat + Thymeleaf模板引擎,并将package打包为可执行的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
我的班级:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TdkApplicationTests {
@Test
public void contextLoads() {
}
}
@Configuration
public class PersistenceConfig {
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public IOTEcoSystemManager iOTEcoSystemManager() {
return new IOTEcoSystemManagerImpl();
}
@Bean
public DeviceEventRepository deviceEventRepository() {
return new JdbcDeviceEventRepository();
}
@Bean
public DeviceRepository deviceRepository() {
return new JdbcDeviceRepository();
}
/**
* Creates an in-memory "books" 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();
}
}
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
public class BookManagerTests {
/**
* The object being tested.
*/
@Autowired
BookManager bookManager;
@Test
public void testfindDeviceByKey() {
Device device = bookManager.findDeviceByKey("C380F");
assertNotNull(device);
assertEquals("C380F", device.getDeviceKey());
assertEquals(1, device.getId().longValue());
}
@Test
public void testfindDeviceByKeyFail() {
Device device = null;
try {
device = bookManager.findDeviceByKey("C380FX");
} catch (EmptyResultDataAccessException erdae) {
assertNotNull(erdae);
}
assertNull(device);
}
}
@Service("bookManager")
public class BookManagerImpl implements BookManager {
...
}
如果我运行了包的所有测试,我收到了这个错误:
unique constraint or index violation; SYS_PK_10092 table: T_COMPANY
因为脚本运行了两次。如果我删除
classes={PersistenceConfig.class}
来自BookManagerTests的我遇到了这个依赖性问题
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
如果我单独运行两项测试,一切正常
答案 0 :(得分:0)
PersistenceConfig及其内容似乎创建了两次:第一次作为普通bean,第二次作为config(右边)。我建议使用所有注释创建单个主测试类,然后从中扩展测试(不带任何注释)。
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class MainTest {
}
public BookManagerTest extends MainTest {
...
}
答案 1 :(得分:0)
对我而言似乎发生了约束验证,因为PersistentConfig被加载了两次,这掩盖了你的第二个问题。 BookManager在哪里定义?如果用@repository注释,你确定你正确地扫描了类路径吗?