如果在 beanshell 脚本中的 FOR 循环中至少存在一个错误条件,我如何使 jmeter 测试失败?

How can i fail jmeter test if there is at least one false condision in FOR loop in beanshell script?

当我从 csv 文件中获取一些名称(如汽车、电话、blabla)时,我使用小 beanshell 脚本进行了测试,我必须在 html 中检查之前测试步骤中的这些名称。我必须将每次检查的结果写在其他文件中。如果在 html 中找不到至少一个名称,我的问题是将此步骤标记为红色。代码在这里:

String Response = prev.getResponseDataAsString();
try {   
            File file = new File(vars.get("pathtocsv"));
            FileReader fr = new FileReader(file);
            BufferedReader reader = new BufferedReader(fr);
            String line = reader.readLine();

            if (line != null) {
                 String[] parts = line.split(",");

                    try{
                        FileWriter fw = new FileWriter(vars.get("pathtoresults"), true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter pw = new  PrintWriter(bw);
                        for(String i : parts) {
                            String utf8String= new String(i.getBytes("windows-1251"), "UTF-8");
                            if(Response.contains(utf8String)){
                                pw.println("Response contain element: " + i);
                            }
                            else{
                                pw.println("!!! Response doesn't contain element: " + i);
                                Failure=true;
                                FailureMessage = "!!! Response doesn't contain element: " + i;
                                log.warn( "!!! Response doesn't contain element " + utf8String); 
                                prev.setResponseCode("400");
                        }


                        }
                        pw.close();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

您可以通过将成功标记为 false 来使父采样器失败:

  prev.setSuccessful(false); 

prev 是 shorthand 到 SampleResult class instance so you can conditionally mark sampler as failed from the PostProcessor using prev.setSuccessful(false) 的方法。


请注意,Beanshell 是 not the recommended scripting option, starting from JMeter version 3.1 users are strongly encouraged to switch to JSR223 Test Elements and Groovy language as Groovy is more Java compliant, has a lot of JDK enhancements and performs much better. See Apache Groovy - Why and How You Should Use It 以获取更多详细信息。