JMETER -为数组中的所有项目填充JSON请求

jgzswidk  于 2023-06-29  发布在  其他
关注(0)|答案(2)|浏览(103)

我对使用JMeter进行测试还很陌生。我有一个JSON块,我想用我从以前的GET请求中创建的三个数组中的值填充它。结构类似于这样:

"books": [
        {
            "publisher": ${publisherName}, //variable but it's the same for all items in this request
            "ISBN": ${isbn_1},  //the next three are from from 3 different arrays 
            "Price": ${price_1},
            "Publisher": ${publisher_1},
            "Static Value that doesn't change": 100
       
        },

        {
            "publisher": ${publisherName}, //variable but it's the same for all items in this request
            "ISBN": ${isbn_2},  //the next three are from from 3 different arrays 
            "Price": ${price_2},
            "Publisher": ${publisher_2},
            "Static Value that will be the same for all items": 100
       
        },
        
    ],

有没有一种方法可以循环动态地添加块,以便我可以在一个请求中发送所有这些项?

aamkag61

aamkag611#

您可以使用任何合适的JSR223测试元素和Groovy来完成它
如果没有看到你的“数组”看起来像什么,很难提出一个全面的解决方案,JSON结构可以像这样创建:

vars.put('publisherName', 'some publisher')
vars.put('isbn_1', 'foo')
vars.put('isbn_2', 'bar')
vars.put('price_1', '123')
vars.put('price_2', '456')
vars.put('publisher_1', 'baz')
vars.put('publisher_2', 'qux')

def arraySize = vars.entrySet().findAll { entry -> entry.getKey().startsWith('isbn_') }.size()

def books = []

1.upto(arraySize, {index ->
    books.add([publisher:vars.get('publisherName'),
               ISBN: vars.get('isbn_' + index),
               Price: vars.get('price_' + index),
               Publisher:vars.get('publisher_' + index),
               "Static Value that doesn't change": 100
    ])
})

log.info(new groovy.json.JsonBuilder([books:books]).toPrettyString())

生成的值可以存储到JMeter变量中,如:

vars.put('payload', new groovy.json.JsonBuilder([books:books]).toPrettyString())

并在以后需要时用作${payload}
更多信息:

t5zmwmid

t5zmwmid2#

我假设你有3个不同的数组,大小相同,分别是ISBNPricePublisher。您将代码写入JSR223 Pre-Processor

import groovy.json.JsonOutput

def books = []

def isbn_list = ['isbn1', 'isbn2', 'isbn3']
def price_list = [100, 200, 300]
def publisher_list = ['A', 'B', 'C']

def publisher = "fix"

for (i = 0; i < isbn_list.size(); i++) {
    def book = [:]
    book['publisher'] = publisher
    book['ISBN'] = isbn_list[i]
    book['Price'] = price_list[i]
    book['Publisher'] = publisher_list[i]
    books.add(book)
}

vars.put('books', JsonOutput.prettyPrint(JsonOutput.toJson(books)))

相关问题