日期:2014-05-16 浏览次数:20477 次
package com.keesail.server; import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import org.dbunit.DatabaseTestCase; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.ext.mysql.MySqlConnection; import org.dbunit.operation.DatabaseOperation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.dao.DataAccessException; import com.keesail.server.model.Person; import com.keesail.server.service.PersonManager; public class DbunitTest extends DatabaseTestCase { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "/applicationContext-resources.xml", "/applicationContext.xml", "/applicationContext-dao.xml" }); @Override protected IDatabaseConnection getConnection() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/supben", "root", "123456"); return new MySqlConnection(con, "supben"); } @Override protected IDataSet getDataSet() throws Exception { return new FlatXmlDataSet(getClass().getResourceAsStream("/person-seed.xml")); } @Override protected DatabaseOperation getSetUpOperation() { return DatabaseOperation.CLEAN_INSERT; } @Override protected DatabaseOperation getTearDownOperation() { return DatabaseOperation.NONE; } public void testFind() { PersonManager personManager = (PersonManager) context.getBean("personManager"); try { List<Person> list = personManager.findByLastName("456"); if (list != null && list.size() > 0) { System.out.println("firstname is " + list.get(0).getFirstName()); } } catch (DataAccessException e) { e.printStackTrace(); } } }
<?xml version="1.0" encoding="UTF-8"?> <dataset> <person id="5" first_name="admin1" last_name="456" /> <person id="6" first_name="admin2" last_name="456" /> <person id="7" first_name="admin3" last_name="456" /> <person id="8" first_name="admin4" last_name="456" /> </dataset>