验证是否调用了受测系统的方法

时间:2016-05-07 10:10:16

标签: java unit-testing junit mocking mockito

我有DatabaseFacade类这三种方法:

public class DatabaseFacadeImpl implements DatabaseFacade {


    private final SQLiteDatabase database;

    public DatabaseFacadeImpl(SQLiteDatabase database) {
        this.database = database;
    }

    @Override
    public long insertOrUpdate(String tableName, ContentValues values, String columnId) throws SQLException {
        try {
            return insertOrThrow(tableName, values);
        } catch (SQLException e) {
            return updateOrThrow(tableName, values, columnId);
        }
    }

    @Override
    public long insertOrThrow(String tableName, ContentValues values) {
        return database.insertOrThrow(tableName, null, values);
    }

    @Override
    public int updateOrThrow(String tableName, ContentValues values, String columnId) throws SQLException {
        final String whereClause = columnId + "=?";
        final String[] whereArgs = {values.getAsString(columnId)};

        return database.update(tableName, values, whereClause, whereArgs);
    }
}

我想在insertOrUpdate中测试,如果插入失败,则调用update方法。现在我和Mockito一样这样做:

@Test
public void insertOrUpdate_withUnSuccessfullInsert_updates() {
    DatabaseFacadeImpl databaseFacade = spy(new DatabaseFacadeImpl(mock(SQLiteDatabase.class)));
    when(databaseFacade.insertOrThrow(tableName, contentValues)).thenThrow(SQLiteException.class);
    final String columnId = "1";
    // databaseFacade.insertOrThrow counts as an invocation
    reset(databaseFacade); 
​
​    // databaseFacade.insertOrUpdate counts as an invocation as well
    databaseFacade.insertOrUpdate(tableName, contentValues, columnId);

    verify(databaseFacade).insertOrUpdate(tableName, contentValues, columnId);
    verify(databaseFacade).insertOrThrow(tableName, contentValues);
    verify(databaseFacade).updateOrThrow(tableName, contentValues, columnId);
    verifyNoMoreInteractions(databaseFacade);
}

问题在于insertOrThrowinsertOrUpdate都被视为调用,因此我必须重置它们或验证它们。

有没有更好的方法呢?

0 个答案:

没有答案