Groovy has been around in Java since 2003. With over a decade of history, development, and experience, it is a Java syntax-compliant object-oriented programming language that compiles to JVM bytecode. In some ways, Groovy can be seen as a scripted version of Java. This is because it runs on the JVM, but because of the way it works, it interoperates well with Java code and its associated libraries. Most valid Java code can also be converted to valid Groovy code.

Groovy was designed to be both a programming language and a scripting language. This means that unlike Java, which needs to be compiled, Groovy can combine the use of various syntactic sugars, reducing a lot of coding effort.

The biggest difference between Groovy and Java code is that Groovy is more flexible and requires fewer syntactic requirements, which appeals to many Java users. This means that many Java developers entering Groovy will find the process of learning it very simple. Because fundamentally, most object-oriented programming languages tend to follow the same syntax. This shared ideology makes it easy for developers to switch between Java and Groovy, or to mix them.

This article will show you some of the first situations you encounter when coding with Groovy to illustrate its features and advantages.

Groovy environment

You can install Groovy through the package manager. Or you can install Groovy from their website, just like Java, provided the Java SDK is the foundation.

Groovy files are saved with the.groovy extension.

You can execute files directly from the command line, for example:

groovy index.groovy

To run the Groovy Shell, type Groovysh directly on the command line.

The list and map

Lists are also commonly called arrays. It stores objects sequentially and can be accessed through integer indexes. In Groovy, the list looks like this:

    def shoppingList = ["flour"."eggs"."banana"."bread"]
 ​
    println shopingList[2]
 ​
    shoppingList.remove("flour")
    
    shoppingList.add("milk")
 ​
    println shoppingList[2]

Copy the code

These are all very basic, and generally consistent with Java List syntax conventions. List in Groovy.

Map contains lists based on key pair values, just like Java.

    def productDetails = [
      "name": "FunTester"."type": "tester"."age": 5."color": "bule"
     ]
 ​
     println productDetails["name"];
     ​
     productDetails["age"] = 5.99
Copy the code

We can also add a list to the map, as follows:

    def toDoList = [
      "monday": ["water plants"."laundry"]."tuesday": ["assignment due"."feed cat"]
     ]
     ​
     toDoList['wednesday'] = ["clean kitchen"."get groceries"]
     ​
     println toDoList['wenesday'] [1]
Copy the code

Of course, we can even access value directly using todolist. Monday.

Conditional statements

The most basic condition is an if else statement. The result is a Boolean value that determines the next block of code to execute. The if else statement in Groovy looks like this:


def myString = "I am FunTester."if(myString.contains("FunTester")){
    println myString
 } else {
    println "NO!"
 }
Copy the code

Groovy can omit the parentheses following the method here.

You can also execute an expression that evaluates to a Boolean in an IF statement. && and | | operators are referred to as “and” and “or” condition, this is in complete accord with Java.

Another condition that you can use to provide if else statement options beyond these two options is to use the else if option.

cycle

A loop is a set of code that we want to repeat in some cases. Common types of loops are: while, each.

Let’s start with the first of the three: the while loop. While writing loops in Groovy looks like this:

     def counter = 0;
     ​
     while(counter < 10){
        counter = counter ++
     }
     ​
     println "FunTester!"
Copy the code

Each is when you work with a list, iterate through it until the list is used up. Each functionality is similar to Java’s foreach functionality, but more powerful. Here is an example of using each to iterate through a list:

    def children = ["James"."Albus"."Lily"];
     ​
     println "The children's names are:"
     children.each { child ->
        println child
     }
Copy the code

Of course, you can also traverse the map like this:

    def families = [
      "Potter": ["James"."Albus"."Lily"]."Weasley": ["Rose"."Hugo"]."Lupin": ["Edward"]
     ]
     ​
     families.each{ family, child ->
      println "The children of the " + family + " family are " + children.join(', ')}Copy the code

JSON

Unlike Java, Groovy comes with JsonBuilder to handle JSON objects, which is rarely used, but is often used in the JMeter API. Mainly because JMeter supports native Groovy scripts, using JsonBuilder eliminates the need to import third-party JSON packages.

Groovy includes simple classes for writing JSON. All you have to do is import and use JsonBuilder on the list map you want to transform.

    import groovy.json.JsonBuilder
     ​
     def families = [
      "Potter": ["James"."Albus"."Lily"]."Weasley": ["Rose"."Hugo"]."Lupin": ["Edward"]]new File('familyMembers.json') < <new JsonBuilder(families).toPrettyString()
Copy the code

NewFile () will create a newFile object to which we will pass the transformed families JSON information. Here, again, the Groovy feature is interesting; if you are interested, just open the source code. Groovy also supports reworking of many operators. See Groovy overload operators (Ultimate edition).

JSON is the most popular way to move structured data between different applications and networks. Let’s assume that we have a JSON file with a huge list of all the inventory information.

    import groovy.json.\*
     ​
     def inventoryListFile = new File('products.json')
     def inventory = new JsonSlurper().parseText(inventoryListFile.text)
     ​
     println inventory['banana']
Copy the code

Create a new instance with JsonSlurper and call the parseText method to read the JSON text information into a JSON object.

HTTP

The same scenario used here can be of great use in the JMeter API scenario, where scripts for HTTP requests can be implemented on machines with only the Java SDK and Groovy SDK. The following example uses closures to parse the response, which is not recommended in practice. Because there is a lack of checking capabilities that native ides provide, both in JMeter and on Linux servers, script readability takes precedence over coding efficiency.

import groovyx.net.http.HTTPBuilder
     import groovy.json.JsonBuilder
     ​
     new HTTPBuilder('http://localhost:12345/te3st').get(
           'query': [
             'action': 'FunTester'.'search': 'funs'
          ]
     ) { resp, json ->
           if(resp.status == 200) {
                 def responseFile = new File('potter.json')
                 responseFile.text =  new JsonBuilder(json).toPrettyString()
          } else {
               println 'Response error &resp.status'}}Copy the code

last

Groovy is a language that makes up for some of Java’s shortcomings, and if you’re a Javaer, you can almost instantly become Groovyer because most of the syntax is compatible. In practice Groovy allows Java to take off in situ.

Have Fun ~ Tester!

  • FunTester test framework architecture diagram
  • JMeter Chinese Operation Manual with a sense of time
  • 140 interview questions (UI, Linux, MySQL, API, security)
  • Graphic HTTP brain map
  • Fiddler Everywhere is the future
  • JVM command brain map for testing
  • The Definitive Guide to Java Performance
  • FunTester Framework Tutorial
  • Tease the interface documentation together
  • Bind mobile phone number performance test
  • Selenium4 Alpha-7 Upgrade experience
  • What happens if you have 100 years of membership
  • LT browser – responsive web testing tool
  • Java NIO is used in interface automation