gpt4 book ai didi

java - PreparedStatementCallback 覆盖率的 Junit 测试用例

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:29 25 4
gpt4 key购买 nike

@Transactional
public Boolean save(final StudentLogEntry studentLogEntry) throws SQLException,DaoException{
boolean returnFlag = true;
String sqlInsert = "insert into STUDENT_DETAILS (INSERT_DATE,STUDENT_NAME,STUDENT_ID) values(SYSDATE,?,?)";
returnFlag = jdbcTemplate.execute(
sqlInsert,
new PreparedStatementCallback<Boolean>() {
Boolean b=false;
@Override
public Boolean doInPreparedStatement(PreparedStatement pst) {
try {
pst.setString(2, studentLogEntry.getStuName());
pst.setString(3, studentLogEntry.getStuId());
b=pst.execute();
} catch (SQLException e) {
clicklogger.info("SQLException has occurred while inserting studentlog ",e);
} catch (DataAccessException e) {
clicklogger.info("DataAccessException has occurred while inserting studentlog ",e);
}
return b;
}
}
);
return returnFlag;
}

我的项目使用Spring框架,我已经为上面的代码编写了Junit测试用例。但我无法涵盖 PreparedStatementCallback。我的测试用例如下:

@Test
public void testSave() throws DaoException, SQLException {
studentDao.setJdbcTemplate(jdbcTemplate);
studentDao.setTransactionManager(transactionManager);
StudentLogEntry studentLogEntry = new StudentLogEntry();
studentLogEntry.getStuName("ABC");
studentLogEntry.getStuId("1234");
assertEquals("true",studentDao.save(studentLogEntry));
}

最佳答案

该方法做了很多工作,使其可以轻松、清晰地进行测试。

1) 我会将新的 PreparedStatementCallback 移至专门的类:

public class MyPreparedStatementCallback implements PreparedStatementCallback<Boolean>{

@Override
public Boolean doInPreparedStatement(PreparedStatement pst) {
....
}

我将在这里单独测试 doInPreparedStatement 方法。应该和之前的测试完全没有关系。

2) 在原始方法中使用新类并测试是否已传递正确的实例(您需要 Mockito here ):

returnFlag = jdbcTemplate.execute(sqlInsert,new MyPreparedStatementCallback());

和测试:

@InjectMocks
StudentDao studentDao;

@Mock
JdbcTemplate jdbcTemplateMock;

@Captor
ArgumentCaptor argCaptor;

@Before
public void init(){
MockitoAnnotations.initMocks(this);
}

@Test
public void shouldSaveWithCallback(){
// Act
// set up
studentDao.save(studentLogEntry);
myClass.userPressedButton();

Mockito.verify(jdbcTemplateMock).execute(Mockito.anyString(), argCaptor.capture());

// Assert
assertTrue(argCaptor.getValue() instance of MyPreparedStatementCallback);
}

底线是您不应该使用原始测试方法来测试该回调的实现。这太多了,您的测试将过于粗糙且难以维护。

关于java - PreparedStatementCallback 覆盖率的 Junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com