测试用例也十分简单:

package com.noyaxe.myapp.repository;

import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.noyaxe.myapp.entity.Floor;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;

import java.util.List;

import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionDbUnitTestExecutionListener.class})
public class FloorDaoTest {
    @Autowired
    private FloorDao floorDao;

    @Test
<PRE class=java name="code">    @DatabaseSetup("FloorDao-findbByBuidlingName-dataset.xml")</PRE>    public void testFindByBuildingName(){        List<Floor> singleFloorList = floorDao.findByBuildingName("SOHO");        assertEquals(1, singleFloorList.size());        List<Floor> twoFloorList = floorDao.findByBuildingName("New Gate Plaza");        assertEquals(2, twoFloorList.size());        List<Floor> emptyFloorList = floorDao.findByBuildingName("Test");        assertEquals(0, emptyFloorList.size());    }    @Test<BR><PRE class=java name="code">    @DatabaseSetup("FloorDao-findbByBuidlingNameAndFloorNum-dataset.xml")</PRE>    public void testFindByBuildingNameAndFloorNum(){        Floor floor = floorDao.findByBuildingNameAndFloorNum("SOHO", 2);        assertNotNull(floor);        Floor empty = floorDao.findByBuildingNameAndFloorNum("New Gate Plaza", 7);        assertNull(empty);        empty = floorDao.findByBuildingNameAndFloorNum("No Building", 7);        assertNull(empty);    }}

  通过代码,可以很清楚的看到通过DatabaseSetup完成了对测试数据的引入。这里在每个测试方法前引入不同的文件,如果所有的方法可以通过一个文件包括,那么也可以在类前面使用DatabaseSetup引入数据文件。

  至此,一个完整的数据层测试用例已经呈现,并且可以运行。可是实际的过程却并没有这么顺利,接下来的文章要总结一下遇到的问题。