2017-05-11 6 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でnullポインタエラーを取得し、このユニットテストを実行してみてください私は思っているだろうが、私は接続を適切に嘲笑していないからだと思う。どのように接続を正しく模擬するのですか?また、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(引数なし)'エラーに適切なメソッドが見つかりません。 –

関連する問題