How do I test a MongoDB connection? Here is my code:
class MongoDB(val SERVER:String, val PORT:Int, val DATABASE: String, val COLLECTION: String){
def establishConnection(): MongoCollection = {
val mongoClient = MongoClient(SERVER, PORT)
println("MongoDB client connection: "+ mongoClient)
val db_handle = mongoClient(DATABASE)
println("Connected to DB : "+ DATABASE)
println("Collections present are :")
println(db_handle.collectionNames)
assert (establishConnection.size > 0 )
db_handle(COLLECTION)
}
def insert(collection : MongoCollection, document : MongoDBObject) : Unit = {
println(collection.insert(document))
}
def find(collection : MongoCollection) = {
println("In find query() :")
val cursor = collection.find()
cursor.toList
}
def find(collection : MongoCollection, obj : MongoDBObject) = {
println("In find query() with condition:")
val cursor = collection.find(obj)
cursor.toList
}
def findOne(collection : MongoCollection) ={
println("In findOne query() :")
val cursor = collection.findOne()
cursor.toList
}
def findOne(collection: MongoCollection, obj : MongoDBObject) ={
println("In findOne query() with condition:")
val cursor = collection.findOne(obj)
cursor.toList
}
def update(collection : MongoCollection, query : MongoDBObject, update : MongoDBObject) = {
val result = collection.update(query, update) //update or findAndModify can be used
result
}
def delete(collection : MongoCollection, query : MongoDBObject) = {
val result = collection.findAndRemove(query);
result
}
}
您可以使用用Java编写的嵌入式mongo ,它首先下载mongo并将其存储在主目录中(仅第一次下载),然后运行它,可以选择mongoDB版本,这是一个示例项目,如何从中使用它斯卡拉测试https://github.com/SimplyScala/scalatest-embedmongo 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.