2017-07-10 73 views
1

我想測試一個數據庫視圖,我使用db-unit將數據插入到被測試的視圖和期望值所使用的表中。表單視圖是由db-unit完成的,但是此視圖使用某些數據形成了另一個我想要的視圖以模擬,我已經做了一些腳本與模擬數據替換視圖,完成測試方法模擬視後替換原來的觀點如何執行第一個@After無效後()從junit然後@ExpectedDatabase從db-unit?

但是我發現一個問題,@ExpectedDatabase之後@After void after()方法調用,測試失敗。

如何從junit執行第一個@After void after(),然後從db-unit執行@ExpectedDatabase

這裏是我的代碼:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = ApplicationConfigTest.class) 
@TestExecutionListeners({ DependencyInjectionTestExecutionListener. DirtiesContextTestExecutionListener.class }) 
public class ClassTest { 

private static final String MOCK_REOURCE_PATH = "classpath:sql/mock_view.sql"; 

private static final String ORIGINAL_REOURCE_PATH = "classpath:sql/original_view.sql"; 

@Autowired 
private ApplicationContext applicationContext; 

@Before 
public void init() { 
    ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(MOCK_REOURCE_PATH)); 
} 

    @Test 
    @DatabaseSetup("classpath:sample-data.xml") 
    @ExpectedDatabase(assertionMode = NON_STRICT, value = "classpath:expected-data.xml") 
    public void testView() { 
    } 

    @After 
    public void after() { 
    ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(ORIGINAL_REOURCE_PATH)); 
    } 
} 
+0

如果更換'@Before會發生什麼'和'@ After'分別用'@ BeforeTransaction'和'@ AfterTransaction'? –

+0

@SamBrannen我試過了,但測試仍然失敗。我認爲db單元在春季交易前有自己的交易 –

+0

你如何配置DbUnit支持?從你發佈的代碼看,DbUnit甚至不可能執行。 –

回答

0

您的@TestExecutionListeners聲明被打破:它不會編譯 「原樣」。

確保您的TransactionalTestExecutionListenerDbUnitTestExecutionListener通過@TestExecutionListeners註冊和註釋您的測試類Spring的@Transactional註釋,類似於下面的東西...

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = ApplicationConfigTest.class) 
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, 
    DirtiesContextTestExecutionListener.class, 
    TransactionalTestExecutionListener.class, 
    DbUnitTestExecutionListener.class }) 
@Transactional 
public class ClassTest { /* ... */ } 
相關問題