Reputation: 7719
I'm trying to test a connection to my Database and trying to configure a Mock Database. I only have no clue how to. How is it possible with any test framework to mock a database and test my method (shown below) getUserById
?
Since this is using raw jdbc, how can I overwrite this getConnection()
method to be using the mock database instead of the real one? Or isn't this the way to go?
I haven't tested a database connection/output of API ever, so I don't know where to start.
This is my jdbc class:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement
import java.util.ArrayList
import java.util.Properties
import bye.domain.*
class jdbcTrial {
val url: String = "jdbc:postgresql://196.21.2.12:5432/events"
//val props: Properties = Properties();
val DB_DRIVER = "org.postgresql.Driver";
// used for getting the comments
fun getUserById(id: Int): User {
val query = "select * from user where id = ${id};";
return getSingleUser(query)
}
/*
Singles
*/
fun getSingleUser(query: String): User {
val conn = this.getConnection()
var user = User()
val statement: Statement = conn.createStatement()
val rs: ResultSet = statement.executeQuery(query)
while (rs.next()) {
user = convertToUser(rs)
}
return user
}
/*
Converting
*/
fun convertToUser(rs: ResultSet): User {
val id = rs.getInt("id")
val uname = rs.getString("username")
val type = rs.getString("usertype")
return User(id, uname, type)
}
fun getConnection(): Connection {
Class.forName(DB_DRIVER).newInstance()
val conn: Connection = DriverManager.getConnection(url, "username", "password")
return conn
}
}
Upvotes: 0
Views: 2399
Reputation: 14550
in the real world you can see at least the following ways:
i recommend the last one using:
Upvotes: 1