0

I have an interface like this:

interface Database {
    fun insertItems(items: List<ItemData>)
    fun deleteItems(items: List<ItemData>)
    fun runTransaction(alsoDelete: Boolean) {
        insertItems(listOf(ItemData(id = 1), ItemData(id = 2), ItemData(id = 3)))
        if (alsoDelete)
            deleteItems(listOf(ItemData(id = 4), ItemData(id = 5), ItemData(id = 6)))
    }
}

I want to use mockk to create instances of Database, but I only want to mock the abstract methods, while keeping runTransaction which does have an implementation that I'd want to test. The result would be that I could then verify like this:

runTransaction(alsoDelete = true)
verify { insertItems(listOf(ItemData(id = 1), ItemData(id = 2), ItemData(id = 3))) }   

Is it possible to achieve this with mockk?

gesuwall
  • 587
  • 2
  • 5
  • 15
  • I believe whenever you want to build upon existing functionality, you should use `spyk` instead of `mockk`. – sschuberth Aug 21 '23 at 15:32

1 Answers1

1

Something alike this should work:

val x = mockk<Database>()

every { x.runTransaction(any()) } answers { callOriginal() }

x.runTransaction(alsoDelete = true)

verify { x.insertItems(listOf(ItemData(id = 1), ItemData(id = 2), ItemData(id = 3))) }

But it's not. I added a ticket here

oleksiyp
  • 2,659
  • 19
  • 15