如何测试MongoDB连接?

时间:2015-03-17 12:06:54

标签: mongodb scala scalatest

如何测试MongoDB连接?这是我的代码:

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
    }
}

1 个答案:

答案 0 :(得分:0)

你可以使用它用java编写的embedded mongo,首先下载mongo并将其存储在主目录中(它只是第一次下载)然后运行它,你可以选择mongoDB版本,这里是一个示例预测如何从scala test https://github.com/SimplyScala/scalatest-embedmongo中使用它。