欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Dbunit 的一个例子

程序员文章站 2022-04-08 14:00:34
...

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>