背景:使用JMeter做接口自动化,用例执行前需要清除一些数据,操作完后校验mongo数据。因为Jmeter3没有对Mongo数据库的支持,所以自己开发java请求实现对mongo的操作。
1.eclipse新建java工程,依赖jar包如下
2.写一个类实现连接mongo数据库,返回要操作的collection对象
public DBCollection ConnectionMongoClient(String host, int port, String dbname,String collection) {
Mongo connection = new Mongo(host,port);
DB db = connection.getDB(dbname);
DBCollection coll = db.getCollection(collection);
return coll;
}
3.参看官网API,java请求需要继承AbstractJavaSamplerClient抽象类,下面以mongo的查询操作为例的实现
sampler核心代码
more details see 点击打开链接
getDefaultParameters:设置请求中的参数以及默认值
public Arguments getDefaultParameters(){
Arguments params=new Arguments();
params.addArgument("ip","127.0.0.1");
params.addArgument("port","27017");
params.addArgument("dbname","dummy");
params.addArgument("collection","users");
params.addArgument("queryjsonString","");
return params;
}
setupTest:参数初始化
public void setupTest(JavaSamplerContext context){
System.out.println("执行setup");
ip= context.getParameter("ip");
port=context.getIntParameter("port");
dbname= context.getParameter("dbname");
collection= context.getParameter("collection");
queryjsonString=context.getParameter("queryjsonString");
}
runTest:操作核心代码:设置请求的名称,执行Mongo的查询,设置查看结果树的响应数据
@Override
public SampleResult runTest(JavaSamplerContext context) {
System.out.println("执行runTest...");
SampleResult sampleresult = new SampleResult();
sampleresult.sampleStart();
//设置sampler请求的名称
sampleresult.setSampleLabel("MongodbSampler" + Thread.currentThread().getId());
//连接mongo
DBCollection coll=new TestMongoConection().ConnectionMongoClient(ip, port, dbname, collection);
DBObject query=new BasicDBObject();
if (queryjsonString!=""&&queryjsonString!=null){
query=(DBObject) com.mongodb.util.JSON.parse(queryjsonString);
}
//日志打印查询条件,查看查询条件是否传值错误
getLogger().debug(query.toString());
DBCursor cursor = coll.find(query);
while (cursor.hasNext()){
DBObject dbobj=cursor.next();
responseData =responseData+dbobj.toString()+ "\n";
}
if ( responseData!= "" || !responseData.equals("")) {
//设置响应数据为查询结果
sampleresult.setResponseData(responseData.getBytes());
}else {
sampleresult.setResponseData(("the return data is null !").getBytes());
}
sampleresult.setSuccessful(true);
sampleresult.sampleEnd();
return sampleresult;
}
删除等操作,仅需修改对mongo操作的相应代码
WriteResult wr=coll.remove(query);
int deleteDocNum=wr.getN();
if (deleteDocNum>0){
responseData=deleteDocNum+" documents deleted successfully";
}else{
responseData="no document deleted";
}
4.界面操作
4.1 请求:
4.2 查看结果,设置的请求名称和响应数据。可对响应数据进行断言,确定用例结果
4.3 将一些关键信息打印入日志,方便调试问题