2017-05-11 3 views
0

저장, 검색 및 삭제와 같은 DB 작업을 수행하는 정적 함수가있는 클래스가 있습니다.유닛 테스트 DB 호출

내 DB 클래스 :이처럼 테스트하는 단위 테스트를 작성

public final class DbUtils { 

    static { 
     DB_USER = //get from secure server 
     DB_PASSWORD = //get from secure server 
    } 


    private static Connection establishConnection() { 
    } 

    private static void closeConnection(Connection connection) { 

    } 

    public static boolean saveObject(final Object graph, final Object map) { 

     Connection connection = establishConnection(); 
     try { 
      byte[] bgraph = ConvertToByte(graph); 
      byte[] bmap = ConvertToByte(map); 
      statement = connection.prepareStatement("INSERT IGNORE INTO " + TABLE_NAME + " VALUES (?,?)"); 
      statement.setObject(1, graph); 
      statement.setObject(2, map); 
      statement.executeUpdate(); 
      //Close statement within try catch 
     } catch(Exception e) { // also other exception 
      //catch to catch all type of exception 
     } 
     closeConnection(connection); 
     return true; 
    } 

    public static Map<String, Object> retrieveObject(final String key) { 
     Connection connection = establishConnection(); 
     //read byte and convert to object 
     closeConnection(connection); 
     return map; 
    } 

    public static boolean deleteObject(final String key) { 
     Connection connection = establishConnection(); 
     //delete all object except object with key 
     closeConnection(connection); 
     return (affectedRow >= 1); 

    } 

} 

:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(DbUtils.class) 
@SuppressStaticInitializationFor("DbUtils") 
public class DbUtilsTest { 

    @Mock 
    Connection connection; 

    @Mock 
    ModuleDependencyGraph dependencyGraph; 

    @Mock 
    private Map<String , String> moduleSDF; 

    @Test 
    public void testSaveObject() throws Exception { 
     PowerMockito.spy(DbUtils.class); 
     PowerMockito.doReturn(connection).when(DbUtils.class, "establishConnection"); 
     Assert.assertTrue(DbUtils.saveObject(dependencyGraph, moduleSDF)); 
    } 
} 

나는 내가 statement = connection.prepareStatement에서 널 포인터 오류가이 단위 테스트를 실행하려고 내가 기대하는 선은 내가 제대로 연결을 조롱하지 않기 때문에 생각합니다. 어떻게 연결을 제대로 조롱합니까? 또한 saveObject 테스트를 작성한 방법이 맞습니까? 나는 베스트 프랙티스와 모든 사례를 다루는 방법을 모르기 때문에 단위 테스트에 익숙하지 않다.

답변

0
@Mock 
Statement statement; 

doReturn(statement).when(connection).prepareStatement(anyString()); 
doNothing().when(statement).setObject(any(), any()); 
doNothing().when(statement).executeUpdate(); 

이것은 단지 모 키토를 사용하고 있습니다. PowerMockito도 사용할 수 있습니다. 그것은 덜 작동해야합니다.

+0

'PowerMockito.doReturn (연결) ...'다음에이 줄을 추가해야합니다. 맞습니까? '@ Mock' 부분을 제외하고. –

+0

예. 'DbUtils.saveObject'가 나오기 전에'setObject'와'executeUpdate'가 에러를냅니다. – pvpkiran

+0

. IDE가 제안하지 않기 때문에 추가 할 가져 오기가 있습니까? 'setObject'는'심볼을 찾을 수 없습니다'에러를주고'executeUpdate'는'executeUpdate (인자 없음)'에러에서 적절한 메소드를 찾지 못했습니다. –