Ustin
Ustin

Reputation: 588

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

I have test with small beanshell-script when i get from csv-file some names (like cars,telephones,blabla) and i have to check this names in html from previous test-step. Result of every check i have to write in other file. My issue here is mark this step to red color if at least one name wasn't find in html. Code here:

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();
        }

Upvotes: 0

Views: 372

Answers (2)

Dmitri T
Dmitri T

Reputation: 168092

prev is a shorthand to SampleResult class instance so you can conditionally mark sampler as failed from the PostProcessor using prev.setSuccessful(false) method.


Be aware that Beanshell is 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 for more details.

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58782

You can fail parent sampler by marking success as false:

  prev.setSuccessful(false); 

Upvotes: 0

Related Questions