https://kotlinlang.org logo
#exposed
Title
# exposed
c

cincue

09/04/2019, 2:30 PM
Hi! Is there any way to simulate a select failure with DSL API during testing?
e

Evan R.

09/04/2019, 8:41 PM
You could use MockK to mock your table to throw
ExposedSQLException
c

cincue

09/05/2019, 3:43 PM
Hi Evan! Could you provide an example? Thanks!
e

Evan R.

09/05/2019, 4:02 PM
Assuming you already have a database table such as this (doing this without an IDE, calls may be slightly incorrect):
Copy code
object MyTable : IntIdTable {
  val name = varchar("name", 128)
}
You can use MockK to mock the “select” method, like:
Copy code
mockkObject(MyTable)
every { MyTable.select(any()) } throws ExposedSQLException( /* Add params for exception here */ )

assertThrows(ExposedSQLException) { MyTable.select { MyTable.id eq 1 } }

// Use this to undo mock
unmockkObject(MyTable)
c

cincue

09/05/2019, 6:08 PM
I'm trying Mockk and I have the same problem as with Mockito, I get "java.lang.IllegalStateException: No transaction in context.", I suspected that It could happen. Any ideas?
e

Evan R.

09/06/2019, 4:40 PM
Sounds like you may be mocking the wrong method. That exception shouldn’t be thrown if the actual method is mocked
c

cincue

09/06/2019, 5:24 PM
I tried with your snippet and It didn't work.
e

Evan R.

09/06/2019, 6:02 PM
Found the issue. Turns out
.select()
is an extension function. The following snippet worked for me:
Copy code
mockkStatic("org.jetbrains.exposed.sql.QueriesKt")
every { MyTable.select(any<Op<Boolean>>()) } throws mockk<ExposedSQLException>()

assertThrows<ExposedSQLException> { MyTable.select { MyTable.id eq 5 } }
Extension functions aren’t actually part of the object itself, they are compiled to static methods on a synthetic class created for the file. To mock it you need to perform a static mock of the file containing the extension function, in this case QueriesKt (from
org.jetbrains.exposed.sql.Queries.kt
)
c

cincue

09/10/2019, 5:06 PM
Great!! Thanks Evan! It works
e

Evan R.

09/11/2019, 3:41 PM
Glad to hear it!
22 Views