使用junit对MyBatis的相关代码进行测试时,为了避免多次重复编写读取中配置文件sqlMapConfig.xml,
我们可以在测试类中书写一个如下方法:
SqlSessionFactory sf;
@Before
public void init() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sf = new SqlSessionFactoryBuilder()
.build(inputStream);
}
完整的例子如下:
package com.tarena.test;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.njupt.pojo.Order;
import com.njupt.pojo.Person;
public class Test1 {
SqlSessionFactory sf;
@Before
public void init() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sf = new SqlSessionFactoryBuilder()
.build(inputStream);
}
}