EasyMock 是一個在單元測試時,用來模擬物件,模擬物件預期行為並加以驗證。
例如 使用 SQL Query 傳回一個 List
Main.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public Listquery(Connection conn) throws SQLException {
Listlist = new ArrayList ();
PreparedStatement ps = conn.prepareStatement("select user from user");
try {
ResultSet rs = ps.executeQuery();
try {
while(rs.next()) {
list.add(rs.getString(1));
}
} finally {
rs.close();
}
} finally {
ps.close();
}
return list;
}
}
若要測試此程式,原本要連 database 建立 table 和 data
使用 EasyMock 就可不連 database 簡化測試
MainTest.java
import static org.easymock.EasyMock.createControl;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.matches;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MainTest {
private Main main;
@Before
public void setUp() throws Exception {
main = new Main();
}
@After
public void tearDown() throws Exception {
main = null;
}
@Test
public void testQuery() throws SQLException {
IMocksControl control = createControl();
// 建立模擬物件
Connection conn = control.createMock(Connection.class);
PreparedStatement ps = control.createMock(PreparedStatement.class);
ResultSet rs = control.createMock(ResultSet.class);
// 模擬物件預期行為
expect(conn.prepareStatement(matches("select user from user"))).andReturn(ps);
expect(ps.executeQuery()).andReturn(rs);
expect(rs.next()).andReturn(true);
expect(rs.getString(1)).andReturn("root");
expect(rs.next()).andReturn(true);
expect(rs.getString(1)).andReturn("tester");
expect(rs.next()).andReturn(false);
rs.close();
ps.close();
// 錄製完成,切到 replay 狀態
control.replay();
// 調用方法
Listexpected = Arrays.asList(new String[]{"root", "tester"});
Listresult = main.query(conn);
assertEquals(expected, result);
// 驗證
control.verify();
}
}
2008年11月1日
EasyMock Test SQL Query
EasyMock
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言