我试图模拟dao类,但我不能模拟dao类,它抛出空指针异常(在dao类中,我使用的是spring jdbc模板)。我也尝试模拟jdbc模板,但它仍然将jdbc模板返回为null。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocationAppDAO.class, BeanPropertyRowMapper.class })
public class CopyOfGeoLocationAppTest {
@Autowired
private ApplicationContext applicationContext;
@Test
@SuppressWarnings({ "unchecked" })
public void testJdbcTemplateforDbase() throws Exception {
// LocationAppDAO locationAppdao= new LocationAppDAO();
String queryWgs84 = "SELECT * FROM location_wgs84 where latitude=" + 0
+ " AND longitude=" + 0;
LocationAppDAO locationAppDaoMock= EasyMock.createMock(LocationAppDAO.class);
JdbcTemplate jdbcTemplateMock = EasyMock.createMock(JdbcTemplate.class);
BeanPropertyRowMapper<Location_wgs84> beanPropertyRowMapperMock = EasyMock
.createMock(BeanPropertyRowMapper.class);
EasyMock.replay(beanPropertyRowMapperMock);
// mocking location
Location_wgs84 location_wgs84mock = EasyMock
.createMock(Location_wgs84.class);
location_wgs84mock.setLatitude(0);
location_wgs84mock.setLongitude(0);
EasyMock.replay(location_wgs84mock);
PowerMock.expectNew(BeanPropertyRowMapper.class).andReturn(
beanPropertyRowMapperMock);
PowerMock.replayAll();
ArrayList<Location_wgs84> arrayList = new ArrayList<Location_wgs84>();
Location_wgs84 location1 = new Location_wgs84();
location1.setLatitude(1);
location1.setLongitude(1);
arrayList.add(location1);
Location_wgs84 location2 = new Location_wgs84();
location2.setLatitude(2);
location2.setLongitude(2);
arrayList.add(location2);
Location_wgs84 location3 = new Location_wgs84();
location3.setLatitude(3);
location3.setLongitude(3);
arrayList.add(location3);
EasyMock.expect(
jdbcTemplateMock.query(queryWgs84, beanPropertyRowMapperMock))
.andStubAnswer(new IAnswer<List<Location_wgs84>>() {
@Override
public List<Location_wgs84> answer() throws Throwable {
return arrayList;
};
});
EasyMock.replay(jdbcTemplateMock);
EasyMock.expect(
locationAppDaoMock.location_wgs84Query(0,0))
.andStubAnswer(new IAnswer<List<Location_wgs84>>() {
@Override
public List<Location_wgs84> answer() throws Throwable {
return arrayList;
};
});
EasyMock.replay(locationAppDaoMock);
LocationAppDAO locationAppdao= new LocationAppDAO();
ReflectionTestUtils.setField(locationAppdao, "jdbcTemplate", jdbcTemplateMock);
List<Location_wgs84> arrayListResult = locationAppdao.location_wgs84Query(0, 0);
assertEquals(3.0, arrayListResult.get(2).getLatitude(), 0);
EasyMock.verify(jdbcTemplateMock);
}
}发布于 2016-01-25 09:49:48
我经常使用H2 database,而不是使用模拟库。我使用DDL设置了一个内存中的数据库,它允许我验证我的应用程序是否对基础表和/或存储过程进行了正确的更改,而不必将测试锁定到数据库访问库的特定部分。
您所需要做的就是在运行测试时提供一个连接字符串,如下所示。它将创建数据库并在任何时候建立连接时运行DDL。
jdbc:h2:mem:example_database;INIT=RUNSCRIPT FROM 'classpath:db/my-example-database.ddl'https://stackoverflow.com/questions/34939470
复制相似问题