使用junit和easymock编写测试代码:public boolean add(Bill bill) { boolean flag = false; Connection connection = null; try { connection = BaseDao.getConnection();//获得连接 connection.setAutoCommit(false);//开启JDBC事务管理 int updateRows = billDao.add(connection,bill); connection.commit(); if(updateRows > 0){ flag = true; System.out.println("add success!"); }else{ System.out.println("add failed!"); } } catch (Exception e) { e.printStackTrace(); try { System.out.println("rollback=================="); connection.rollback();//失败就回滚 } catch (SQLException e1) { e1.printStackTrace(); } }finally{ //在service层进行connection连接的关闭 BaseDao.closeResource(connection, null, null); } return flag; }
时间: 2024-02-14 13:07:50 浏览: 87
以下是使用junit和easymock编写测试代码的示例:
```
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
public class BillServiceTest {
private BillDao billDao;
private BillService billService;
@Before
public void setUp() {
billDao = EasyMock.createMock(BillDao.class);
billService = new BillService(billDao);
}
@Test
public void testAddBill() throws Exception {
Connection connection = EasyMock.createMock(Connection.class);
Bill bill = new Bill();
EasyMock.expect(billDao.add(connection, bill)).andReturn(1);
EasyMock.expectLastCall().once();
EasyMock.expect(connection.getAutoCommit()).andReturn(false);
EasyMock.expectLastCall().once();
connection.commit();
EasyMock.expectLastCall().once();
EasyMock.expect(connection.getAutoCommit()).andReturn(true);
EasyMock.expectLastCall().once();
connection.close();
EasyMock.expectLastCall().once();
EasyMock.replay(billDao, connection);
boolean result = billService.addBill(connection, bill);
Assert.assertTrue(result);
EasyMock.verify(billDao, connection);
}
}
```
在这个例子中,我们使用EasyMock框架来模拟Connection和BillDao的对象,然后设置模拟对象的行为。在测试方法中,我们首先创建Connection和Bill对象,然后使用EasyMock.expect()来设置模拟对象的行为。最后,我们调用EasyMock.replay()来准备模拟对象,然后调用被测试的方法并进行断言。最后,我们调用EasyMock.verify()来验证模拟对象的行为是否符合预期。
阅读全文