tostao
tostao

Reputation: 3048

How init DB with database-unit (Table not found in statement)?

I have a simple spring project and try to use spring-dbunit to do some services tests. I use jdbcTemplate for DB access. Beans configuration:

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" c:dataSource-ref="dataSource"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:springtestdbunit"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

Test class looks like:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"/it/tostao/sswa/sswai-test.xml"})
    @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class})
    public class CarServiceImplTest {

        Logger LOG = LoggerFactory.getLogger(CarServiceImplTest.class);

        @Autowired
        private JdbcTemplate jdbcTemplate;

        private CarService carService;

        @Before
        public void setUp() {
            carService = new CarServiceImpl(jdbcTemplate);
        }

        /**
         * Test cars counter.
         */
        @Test
        @DatabaseSetup("cars.xml")
        public void checkCounter() {
            int nbOfCarsInGarage = carService.sizeInGarage();//SELECT count(*) from car;
            LOG.info("No of cars = " + nbOfCarsInGarage);
            Assert.assertEquals(2, nbOfCarsInGarage);
        }    
}

Cars.xml is a simply data set:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <car brand="BMW" model="E91" year="2006" doorsNumber="5" plate="XXX1234" />
    <car brand="Hyundai" model="Accent" year="2000" doorsNumber="4" plate="YYY333" />
</dataset>

I have to errors in configuration, but when call carService.sizeInGarage() I see message:

org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [SELECT count() FROM car]; nested exception is java.sql.SQLException: Table not found in statement [SELECT count() FROM car]

Should I init DB before run test or problem is with @DatabaseSetup and cannnot find xml file? How check that hsqldb started and working correct?

Upvotes: 0

Views: 883

Answers (1)

user4695271
user4695271

Reputation:

You need to provide a way to create your schema before running your unit tests. The way DbUnit works is by putting your database in a "known state" before running the particular test.

If you have a RDBMS installed, you should have already the database created; but if you are using an in-memory database (more likely for this matters) you must provide a SQL script (or some other way) to be able to create the schema for you when the in-memory database is started.

Have a look here, this may helps.

Upvotes: 1

Related Questions