Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
First steps in using Kotlin, Exposed, and writing tests
import io.kotlintest.Description
import io.kotlintest.Spec
import io.kotlintest.extensions.TestListener
import io.kotlintest.shouldBe
import io.kotlintest.specs.FreeSpec
import org.jetbrains.exposed.dao.EntityID
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.IntIdTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
object Persons : IntIdTable("persons") {
val name = varchar("name", length = 100)
// How do I check that this value is positive?
val age = integer("age_in_years")
}
class Person(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Person>(Persons)
var name by Persons.name
var age by Persons.age
}
object ConnectToDatabase : TestListener {
var database: Database? = null
override fun beforeSpec(description: Description, spec: Spec) {
ConnectToDatabase.database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
}
}
class DocumentConnectToDatabaseWithExposed : FreeSpec() {
override fun listeners(): List<TestListener> = listOf(ConnectToDatabase)
init {
"Basic round trip: connect, create table, insert data, select data" {
transaction(ConnectToDatabase.database) {
SchemaUtils.create(Persons)
Persons.insert {
it[name] = "J. B. Rainsberger"
it[age] = 44
}
val selectAllPersons = Persons.selectAll()
selectAllPersons.count() shouldBe 1
val onlyRow = selectAllPersons.iterator().next()
onlyRow[Persons.id] shouldBe firstValueFromAutoincrementColumn(Persons)
onlyRow[Persons.name] shouldBe "J. B. Rainsberger"
onlyRow[Persons.age] shouldBe 44
}
}
"Basic round trip, Data Access Object style" {
transaction(ConnectToDatabase.database) {
SchemaUtils.create(Persons)
// insert (!)
val jbrains = Person.new {
name = "J. B. Rainsberger"
age = 44
}
val allPersons = Person.all()
allPersons.count() shouldBe 1
val thePerson = allPersons.iterator().next()
thePerson shouldBe jbrains
thePerson.id shouldBe firstValueFromAutoincrementColumn(Persons)
thePerson.name shouldBe "J. B. Rainsberger"
thePerson.age shouldBe 44
}
}
}
}
private fun firstValueFromAutoincrementColumn(table: IntIdTable) = EntityID(1, table)
@jbrains
Copy link
Author

jbrains commented Nov 4, 2018

I tried moving SchemaUtils.create(Persons) up into the ConnectToDatabase listener in order to remove duplication, but I couldn't figure out how to make the transaction in the test see the table created by the transaction in the test listener. Does using an in-memory database stop me from removing duplication that way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment