我有一系列的集成測試,我想測試我的彈簧mvc /彈簧數據jpa堆棧。不幸的是,構建時間很荒謬,而且每次新的集成測試只會變得更糟。它看起來就好像每個單獨的測試會通創建嵌入數據庫,bean創建等如何高效地創建基礎測試類的彈簧mvc集成測試
我有一個基礎測試類的開銷:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { JpaConfig.class })
public class BaseItegration {
private static EmbeddedDatabase database;
@BeforeClass
public static void setUp() throws Exception {
database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).setName("mydb")
.addScript("classpath:embeddedDatabase.sql").build();
}
@Test
public void testInit() {
Assert.assertNotNull(database);
}
凡我JpaConfig.java:
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "org.myproject.service", "org.myproject.utility",
"org.myproject.controller", "org.myproject.utility.startup",
"org.myproject.security" })
@ImportResource({ "classpath:applicationContext.xml", "classpath:myproject-spring-security.xml" })
public class JpaConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {...}
@Bean
public DataSource dataSource() {...}
<etc>
}
然後最後我嘗試使用它,例如:
@TransactionConfiguration(defaultRollback = true)
@Transactional(propagation = Propagation.NESTED)
public class TestContactTypesIT extends BaseItegration {
@Autowired
private ContactTypeRefRepository contactTypeRepository;
@Test
public void testRepositoryNotNull() {
Assert.assertNotNull(contactTypeRepository);
}
...}
在觀看布維ld日誌,我可以看到每個測試的應用程序啓動。有沒有辦法讓BaseIntegrationTest只啓動一個,每個測試都使用該應用程序上下文和嵌入數據庫?
========
更新
我改變了我的JpaConfig這樣:
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).setName("mydb")
.addScript("classpath:embeddedDatabase.sql").build();
}
和我BaseIntegration現在是空的:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { JpaConfig.class })
public abstract class BaseItegration {
}
這裏是因爲錯誤而失敗的測試之一:
InvalidDataAccessResourceUsageException (Table "ADDRESSTYPEREF" not found; SQL statement:
@TransactionConfiguration(defaultRollback = true)
@Transactional(propagation = Propagation.NESTED)
public class TestSeedAddressTypesIT extends BaseItegration {
@Autowired
private AddressTypeRefRepository addressTypeRepository;
@Autowired
private SeedAddressTypes seedAddressTypes;
// hack because we can't do a BeforeClass with Autowired
private boolean seeded = false;
@Test
public void testRepositoryNotNull() {
Assert.assertNotNull(addressTypeRepository);
}
@Test
public void testPopulatedDB() {
if (!seeded) {
seedAddressTypes.seed();
seeded = true;
}
List<AddressTypeRef> addressTypes = addressTypeRepository.findAll();
Assert.assertEquals(5, addressTypes.size());
}
}
然而,所有的集成測試似乎重新ApplicationContext的和嵌入式數據庫。雖然構建日誌不顯示正在創建的數據源,但我確實看到每個集成測試都創建一個新的log4j文件,45個測試需要15分鐘才能生成。
AFAIK,不應該爲每個測試重新創建spring上下文。你如何運行測試?你確定你沒有配置測試運行器爲每個測試產生一個新的JVM嗎? –
我正在使用「mvn clean verify」構建WAR文件。 – sonoerin