[問題] 關於mybatis的uni test
由於公司要求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();
}
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 113.196.174.254
※ 文章網址: https://www.ptt.cc/bbs/java/M.1518418666.A.622.html
→
02/12 15:31,
6年前
, 1F
02/12 15:31, 1F
→
02/12 15:47,
6年前
, 2F
02/12 15:47, 2F
→
02/12 15:48,
6年前
, 3F
02/12 15:48, 3F
→
02/12 15:48,
6年前
, 4F
02/12 15:48, 4F
java 近期熱門文章
PTT數位生活區 即時熱門文章