What is a Mock Object?
Unit testing is the testing of software units in isolation. However, most units do not work alone, but they collaborate with other units. To test a unit in isolation, we have to simulate the collaborators in the test.
A Mock Object is a test-oriented replacement for a collaborator. It is configured to simulate the object that it replaces in a simple way.
EasyMock has been the first dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them.
一个将被Mock:使用JDBC连接DB,得到Table Student的记录
package wei.peng.easymock;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 一个用于连接DB得到数据记录的类
* @author WPeng
*/
public class BeMockObject {
public int getRecordNum(){
int record = 0;
Connection conn;
Statement stmt;
try {
// Load JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Connection
String url = "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName";
conn = DriverManager.getConnection(url, "wpeng", "***" );
// Create Statement
stmt = conn.createStatement();
// Query
String sql = "SELECT COUNT(*) FROM student";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
record = rs.getInt(1);
}
try {
if(!conn.isClosed()){
conn.close();
}
} catch (SQLException e2) {
// TODO: handle exception
}
} catch (Exception e) {
// TODO: handle exception
}
return record;
}
}
一个JUnit Test Case:Mock一个BeMockObject
package wei.peng.easymock;
import org.easymock.EasyMock;
import junit.framework.TestCase;
public class MainTest extends TestCase{
public void testGetRecordNum(){
int expected = 100;
BeMockObject beMockObject = EasyMock.createMock(BeMockObject.class);
EasyMock.expect(beMockObject.getRecordNum()).andReturn(100);
EasyMock.replay(beMockObject);
assertEquals(expected, beMockObject.getRecordNum());
}
}