使用jmeter往指定文件中插入一定數量的數據


有一個需求,新建一批賬號,把獲取的賬號相關信息存入文本文件,當文本文件保存的數據達到一定的數量,就自動停止新建賬號。

 分析下需求:

1、把賬號信息保存到文件,需要使用bean shell腳本(bean shell腳本語法和java一樣,功能也一樣),並且需往腳本中傳入要保存的信息

2、文件中保存的數據達到一定的數量,就自動停止新建賬號。數量也是要用bean shell腳本讀文件獲取文件行數,並傳出。自動停止新建腳本,這就需要價格jmeter的if控制器,在if控制器的條件中判斷數量是否達到。

 

腳本實現過程:

1、位了模擬得到賬號信息,先設置一個User Defined Variables,通過add > config element > User Defined Variables 添加

 

 在User Defined Variables 中添加一個變量account_info,值隨意給就可以,如“111111111111”,這樣往文件中保存“111111111111”模擬為賬號信息

 

 

2、新建一個bean shell 腳本,讀取獲取文件行數

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

int count = 0;
try{
    File file = new File("E:\\test.txt");
    // 如果文件不存在就新建
    if (!file.exists())
    { 
        file.createNewFile();
    }  
    // 讀文件
    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8"));
    // 循環獲取文件行數
    while ((str=bufferedReader.readLine())!=null)
    { 
        count = count + 1;
    }
    bufferedReader.close(); 

}catch(IOException e)
{
    e.printStackTrace();
}
//文件行數java變量傳給jmeter變量total_lines
vars.put("total_lines",String.valueOf(count));

 

3、新建一個if 控制器

 

 

if 控制器里面的條件填寫:

${__jexl3(${total_lines}<11,aa)},其中total_lines 是bean_shell腳本返回的。使用${__jexl3(${total_lines}<11,aa)} 對${total_lines}<11進行判斷並返回true 或false

 

 

4、再在if控制器中新建一個 寫文件bean shell

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
// 傳入jmeter 變量 account  ,使用java變量 message接收
String message= vars.get("account_info");
try{
    File file = new File("E:\\test.txt");
    // 如果文件不存在,就新建一個文件
    if (!file.exists())
    { 
        file.createNewFile();
    }
    // 文件末尾追加寫入文件  
    FileOutputStream fos = new FileOutputStream(file.getAbsoluteFile(),true);
     fos.write(message.getBytes());  
     fos.write("\n".getBytes());  
     fos.close();
}catch(IOException e)
{
    e.printStackTrace();
}

整個jmeter 腳本結構形式

 

歡迎關注微信公眾號:為測,獲取更多技術干貨資料

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM