Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Proposal] Support Library for mocking SQLDelight queries #22

Open
Nillerr opened this issue Dec 27, 2021 · 1 comment
Open

[Proposal] Support Library for mocking SQLDelight queries #22

Nillerr opened this issue Dec 27, 2021 · 1 comment
Assignees
Labels

Comments

@Nillerr
Copy link
Collaborator

Nillerr commented Dec 27, 2021

SQLDeligth is commonly used in Kotlin Multiplatform projects for state management. The generated queries can trivially be stubbed with Mockative given a few additional tools, which could be provided by a support library for mocking SQLDelight queries using Mockative, or as a non-mockative extension library. In particular, adding code like the following two classes will enable stubbing of SQLDelight generated queries using Mockative:

class IteratorCursor<RowType : Any>(private val results: Iterator<RowType>) : SqlCursor {
    // Could also use AtomicRef from `kotlinx.atomicfu`
    private var _current: RowType? by AtomicReference(null)
    
    // Could also use `by atomic()` from `kotlinx.atomicfu`
    private var isClosed: Boolean by atomic(false)

    val current: RowType?
        get() = _current

    override fun close() {
        isClosed = true
    }

    override fun getBytes(index: Int) = throw IllegalStateException()
    override fun getDouble(index: Int) = throw IllegalStateException()
    override fun getLong(index: Int) = throw IllegalStateException()
    override fun getString(index: Int) = throw IllegalStateException()

    override fun next(): Boolean {
        if (isClosed) {
            throw IllegalStateException("The cursor is closed")
        }
        
        if (results.hasNext()) {
            _current = results.next()
            return true
        }

        return false
    }

}
class IterableQuery<RowType : Any>(private val results: Iterable<RowType>) : Query<RowType>(
    queries = mutableListOf(),
    mapper = { cursor -> @Suppress("UNCHECKED_CAST") (cursor as IteratorCursor<RowType>).current!! }
) {
    override fun execute() = IteratorCursor(results.iterator())
}

Having these pieces you could write test stub code like the following:

given(queries).invocation { getOfflineRatesByBase(currencyResponse.base) }
  .thenReturn(IterableQuery(listOf(offlineRates)))
@abueide
Copy link

abueide commented Nov 10, 2022

if anyone wanted to work on this i'd chip in $25

@Nillerr Nillerr self-assigned this Apr 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants