利用EasyMock生成数据库连接简单测试示例
Posted luzhouxiaoshuai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用EasyMock生成数据库连接简单测试示例相关的知识,希望对你有一定的参考价值。
package demo.mock; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class LoginAction{ public String login(Connection conn, String name, int pas) { PreparedStatement pst = null; ResultSet rs = null; try { String sql = "select * from user where name = ? and pas = ?"; pst = conn.prepareStatement(sql); pst.setString(1, name); pst.setInt(2, pas); rs = pst.executeQuery(); if(rs.next()) { return "登陆成功。"; } else { return "登陆失败。"; } }catch(SQLException e) { e.printStackTrace(); return "抛出异常。"; } finally { try { rs.close(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } } package demo.mock; import static org.easymock.EasyMock.createControl; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.easymock.IMocksControl; import org.junit.After; import org.junit.Before; import org.junit.Test; public class LoginActionTest { private LoginAction login; @Before public void init() { login = new LoginAction(); } @After public void destory() { login = null; } @Test public void login() throws SQLException{ String name = "admin"; int pas = 123; //创建Mock对象 IMocksControl control = createControl(); //创建多个Mock对象时通过IMocksControl管理 Connection conn = control.createMock(Connection.class); PreparedStatement pst = control.createMock(PreparedStatement.class); ResultSet rs = control.createMock(ResultSet.class); // 录制信息,即设定Mock对象的预期行为和输出 // 所有Mock对象需要执行的方法都必须录制,如pst.setInt(2, pas)、rs.close()等 String sql = "select * from user where name = ? and pas = ?"; expect(conn.prepareStatement(sql)).andReturn(pst).times(1); pst.setString(1, name); pst.setInt(2, pas); expect(pst.executeQuery()).andReturn(rs); expect(rs.next()).andReturn(true); rs.close(); pst.close(); //录制完成,切换replay状态 control.replay(); //调用实际的方法 String res = login.login(conn, name, pas); String expected = "登陆成功。"; assertEquals(expected, res); //验证 control.verify(); } }
以上是关于利用EasyMock生成数据库连接简单测试示例的主要内容,如果未能解决你的问题,请参考以下文章