jmeter-13 - Use JSR223 assertions (recommended)


Preface

I have been using BeanShell before and after, assertions, etc., but when I checked the official documentation, I found that it is recommended to use JSR223. In fact, BeanShell is a type of JSR223. Let's continue to learn more.
Official website introduction: Apache JMeter - User's Manual: Component Reference
Insert image description here
Translation: It is strongly recommended to migrate to JSR223 Assertion+Groovy to improve performance, support new Java features and limited maintenance of the BeanShell library.

By understanding JSR223, Jmeter can provide a variety of scripting languages ​​to achieve the functions you want to achieve, as shown below.
Insert image description here
There are many scripting languages ​​to choose from, and of course there are others such as python, etc.


1. JSR 223 making assertions

1. For example, response json:

{
    
    "hello":"app1"}

2. JSR223 assertion
The response code and response content include header, cookie, and body. We can make assertions based on the following content.

// 获取http响应代码
def httpCode = prev.getResponseCode()

// 获取http响应body
def response = prev.getResponseDataAsString()

// 获取响应的所有header
def headers = prev.getResponseHeaders()

// 获取响应的cookie
def cookies = prev.getCookies()

3. http response status code assertion

if(prev.getResponseCode().equals("200")){
    
     
	Failure=false;	// 断言成功
}
else{
    
    
	Failure=true;	// 断言失败
	FailureMessage="http code != 200";  // 自定义失败信息
}

4. http response body assertion

import groovy.json.JsonSlurper

// 获取响应
def response = prev.getResponseDataAsString()

// 解析为JSON响应
def jsonResponse = new JsonSlurper().parseText(response)
// JSON响应,获取所需的值
def value = jsonResponse.hello

// 进行断言期望值
def expValue = "app2"

// ① expValue in response            ② expValue == value
if (response.contains(expValue) || value.equals(expValue)){
    
    
    // 断言成功
    AssertionResult.setFailure(false)
} else {
    
    
    // 断言失败
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Assertion failed. Expected value: ${expValue}. Actual value: ${value}")
}


fail:
Insert image description here


2. Summary

Although the above writing method seems simple, it is enough!
Overall it's pretty good, you can make assertions freely, and it's needed for some complex scenarios.

Guess you like

Origin blog.csdn.net/qq_42675140/article/details/131363103