2017-12-05 4 views
1
@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을 다룰 수 없습니다. 내 테스트 케이스는 다음과 같습니다.PreparedStatementCallback 적용 범위에 대한 Junit 테스트 케이스

@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)); 
} 
+0

테스트를 실행하는 동안'save' 메소드를 디버깅하려 했습니까? 특히'jdbcTemplate.execute (...)'를 호출하십시오. –

+1

예 테스트하는 동안 save 메소드를 디버깅했습니다. doInPreparedStatement 내부에 입력하면 컨트롤이 실패합니다. –

답변

0

이 메소드는 쉽고 명확하게 테스트 할 수 있도록하기 위해 노력하고 있습니다.

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); 
} 

하단의은 원래 테스트 방법으로 해당 콜백의 구현을 테스트해서는 안된다는 것입니다. 너무 많아서 테스트는 거칠고 유지하기가 어려울 것입니다.

관련 문제