2

I want to test a database view and I use db-unit to insert data into tables which are used by tested view and expected values form view is done by db-unit, but this view use some data form another view which I want to mock, I have done some a script which replace view with mock data, after finishing test method mock view is replaced with original view

But I find a problem, @ExpectedDatabase is invoked after @After void after() method, and test fails.

How can I execute first @After void after() from junit and then @ExpectedDatabase from db-unit?

Here is my code:

@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 ));
  }
}

1 Answers1

1

Your declaration for @TestExecutionListeners is broken: it doesn't compile "as is".

Make sure you register the TransactionalTestExecutionListener and the DbUnitTestExecutionListener via @TestExecutionListeners, and annotate your test class with Spring's @Transactional annotation, something similar to the following...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfigTest.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })
@Transactional
public class ClassTest { /* ... */ }
Sam Brannen
  • 29,611
  • 5
  • 104
  • 136