[問題] 關於mybatis的uni test

作者: angleevil (朦朧尋光)   2018-02-12 14:57:40
由於公司要求mybatis產生的code gen也需要uni-test.
參考此網站
https://github.com/mybatis/mybatis-3/wiki/Unit-Test
撰寫以下測試程式, 我先用befor去add資料, 再用test去測試select的資料,但是每次得到都是null. 目前理解是會存到in-memory database.
所以不會對真實的db做操作, 但是不理解為何無法select資料.不知道大家有甚麼方向嗎??
public class BaseTest {
protected static SqlSessionFactory sqlSessionFactory;
@Inject
private CommunityDAO communityDAO;
private final Integer page = 1;
private final Integer range = 8;
private Integer communityId = 0;
private final String name = "comm1";
private final String desc = "desc1";
private final String userId = "u000001";
private final String nameUpdate = "comm2";
private final String descUpdate = "desc2";
private final String userIdUpdate = "u000002";
@BeforeClass
public static void setUpClass() throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
SqlSession session = sqlSessionFactory.openSession();
Connection conn = session.getConnection();
reader = Resources.getResourceAsReader("sql/schema.sql");
ScriptRunner runner = new ScriptRunner(conn);
runner.setLogWriter(null);
runner.runScript(reader);
conn.close();
reader.close();
session.close();
}
@Before
public void setUp() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
communityDAO = sqlSession.getMapper(CommunityDAO.class);
CommunityInfo communityInfo = new CommunityInfo();
Date dNow = new Date();
long milliseconds = dNow.getTime();
communityInfo.setName(name);
communityInfo.setDesc(desc);
communityInfo.setUserId(userId);
communityInfo.setDate(milliseconds);
communityInfo.setType(TypeEnum.PUBLIC.toString());
communityInfo.setStatus(StatusEnum.OPEN.toString());
communityInfo.setCategory(CategoryEnum.COMMON.toString());
communityDAO.add(communityInfo);<==add 資料
communityId = communityInfo.getCommunityId(); <== 此sql的欄位是community_id是auto_increment會自動增長
} finally {
sqlSession.close();
}
}
@Test
public void getCommunityById() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
communityDAO = sqlSession.getMapper(CommunityDAO.class);
CommunityInfo communityInfo = communityDAO.getCommunityById(communityId); <== select資料
System.out.println(communityInfo+"xxxxxxxxxxxxxx"); <==== 每次都是null
Assert.assertEquals("" , communityInfo.getName()); <====所以都不過
} finally {
sqlSession.close();
}
}
}
作者: kniver999 (小囧)   2018-02-12 15:31:00
塞完後在同一個方法中馬上查詢有東西嗎?
作者: angleevil (朦朧尋光)   2018-02-12 15:47:00
剛剛主管幫忙看,add完後, 在select就有. 但是分兩段第二段api的select就沒東西, 可是看範例, 不是存在記憶體嘛??

Links booklink

Contact Us: admin [ a t ] ucptt.com