简体   繁体   中英

soapui + groovy + mongo db assert issue

With given code I try to connect to mongo db than, select event by Event type, than assert for what I just selected

@Grab('org.mongodb:mongodb-driver:3.4.1')

import com.mongodb.MongoClient
import com.mongodb.MongoClientURI
import com.mongodb.DBCollection
import com.mongodb.DB
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject
import com.mongodb.DBObject;
import groovy.json.JsonSlurper;

class MongoService {
    private MongoClient mongoClient

    def login = "user"
    def password = "pass"
    def host = "host"
    def port = port
    def databaseName = 'mongodb'

    public MongoClient client() {
        mongoClient = new MongoClient(new MongoClientURI(
               new StringBuilder("mongodb://").
               append(login).append(":").
               append(password).append("@").
               append(host).append(":").
               append(port).append("/").
               append(databaseName).toString()))
                              ;

        return mongoClient
    }

    public DBCollection collection(collectionName) {
        DB db = client().getDB(databaseName)

        return db.getCollection(collectionName)
    }
}

def service = new MongoService(databaseName: 'mongodb') 
def foo = service.collection('events')

BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("EventType", "test");

    DBCursor cursor = foo.find(whereQuery);
    while (cursor.hasNext()) {
        log.info(cursor.next())

    }
    def json = cursor.next()

    def slurper = new groovy.json.JsonSlurper()
     def result = slurper.parseText(json)
      assert result.EventType == "test"

I return soapui returns java.util.NoSuchElementException error at line:52 Manual chceck in mongodb with same query db.getCollection('events').find({"EventType": "test"}) returns 1 object. I have no idea how to make it work... :/

The problem is the way you're accessing the cursor.

You have already exhausted the cursor when you call log.info(cursor.next()) and when you do cursor.next() there is no element to access and is the reason for that exception.

DBCursor cursor = foo.find(whereQuery);
while (cursor.hasNext()) {
    log.info(cursor.next())
}
def json = cursor.next()

So the fix will be to change your code to call cursor.next() one each iteration in the while loop.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM