2013-04-09 40 views
2

我的單元測試配置是:JUnit,DBUnit,Spring。在單元測試期間回滾自動生成的表值

在我的Spring上下文我有一個嵌入式數據庫 -

<jdbc:embedded-database id="dataSourceSpied"> 
    <jdbc:script location="classpath:test_ddl.sql"/> 
</jdbc:embedded-database> 

我的單元測試來與下面的類級別的註解:

@ContextConfiguration(locations = "classpath:/test-context.xml") 
@RunWith(SpringJUnit4ClassRunner.class) 
@Transactional 
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, 
     TransactionDbUnitTestExecutionListener.class, 
     DbUnitTestExecutionListener.class}) 

我的測試模式有如下片段:

CREATE TABLE test(
    id BIGINT GENERATED BY DEFAULT AS IDENTITY, 
    name VARCHAR(255) NOT NULL, 
    ... 
); 

@Transactional annotati在回滾期間,我在單個單元測試方法中做出的任何更改未清除id值!自動生成的id值不會重置,因此單元測試依賴於它們的運行順序!

如何在測試過程中重置Spring中自動生成的HSQLDB數據庫字段?


也許trucate命令將幫助?

+0

你就不能忽視在測試中的ID值? – Keppil 2013-04-09 06:45:06

+1

我想檢查外鍵是否設置正確,這些外鍵是指自動生成的'id' – 2013-04-09 06:46:51

回答

0

在您的示例中,可以修改自動生成的IDENTITY。

ALTER TABLE test ALTER COLUMN id RESTART WITH 0 

見指南:

http://www.hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_table_manupulation

+0

不錯的想法,你能舉一個例子來說明如何將它與Spring/JUnit集成嗎? – 2013-04-09 17:43:14

+0

編號瞭解如何在每次測試之前或之後運行此聲明。 – fredt 2013-04-09 20:04:34

+0

這不是'@ After'簡單。 DBUnit在'@ After'後測試數據庫狀態,lol。 – 2013-04-10 06:27:35