[英]Running tests in Spring Boot
我有這個測試課
我已經使用Spring Initializr,嵌入式Tomcat + Thymeleaf模板引擎生成了Spring Boot Web應用程序,並將其打包為可執行的JAR文件。
使用的技術:
Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat嵌入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)}
如果我分別運行兩個測試,一切正常
PersistenceConfig及其內容似乎創建了兩次:第一次是作為普通bean,第二次是作為config(是正確的)。 我建議創建帶有所有注釋的單個主測試類,然后從中擴展您的測試(無任何注釋)。
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class MainTest {
}
public BookManagerTest extends MainTest {
...
}
在我看來,約束驗證的發生是因為PersistentConfig被加載了兩次,這掩蓋了您的第二個問題。 BookManager在哪里定義? 如果使用@repository進行了注釋,您確定要正確掃描類路徑嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.