REST-assured with Groovy – 用Groovy保证REST的安全

最后修改: 2018年 3月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll take a look at using the REST-assured library with Groovy.

在本教程中,我们将看看如何使用Groovy的REST-assured库。

Since REST-assured uses Groovy under the hood, we actually have the opportunity to use raw Groovy syntax to create more powerful test cases. This is where the framework really comes to life.

由于REST-assured在后台使用Groovy,我们实际上有机会使用原始Groovy语法来创建更强大的测试案例。这就是该框架真正发挥作用的地方。

For the setup necessary to use REST-assured, check out our previous article.

关于使用REST-assured的必要设置,请查看我们的以前的文章

2. Groovy’s Collection API

2.Groovy的集合API

Let’s start by taking a quick look at some basic Groovy concepts – with a few simple examples to equip us with just what we need.

让我们先快速浏览一下Groovy的一些基本概念–用几个简单的例子来让我们掌握我们所需要的东西。

2.1. The findAll Method

2.1.找到所有的方法

In this example, we’ll just pay attention to methods, closures and the it implicit variable. Let’s first create a Groovy collection of words:

在这个例子中,我们只注意methodsclosuresit隐式变量。让我们首先创建一个Groovy的词语集合。

def words = ['ant', 'buffalo', 'cat', 'dinosaur']

Let’s now create another collection out of the above with words with lengths that exceed four letters:

现在让我们在上面的基础上再创建一个长度超过四个字母的词的集合。

def wordsWithSizeGreaterThanFour = words.findAll { it.length() > 4 }

Here, findAll() is a method applied to the collection with a closure applied to the method. The method defines what logic to apply to the collection and the closure gives the method a predicate to customize the logic.

在这里,findAll()是一个应用于集合的方法,并有一个closure应用于该方法。method定义了应用于集合的逻辑,closure给了方法一个谓词来定制逻辑。

We’re telling Groovy to loop through the collection and find all words whose length is greater than four and return the result into a new collection.

我们要告诉Groovy在这个集合中进行循环,找到所有长度大于4的词,并将结果返回到一个新的集合。

2.2. The it Variable

2.2.变量

The implicit variable it holds the current word in the loop. The new collection wordsWithSizeGreaterThanFour will contain the words buffalo and dinosaur.

隐含变量it保持循环中的当前单词。新的集合wordsWithSizeGreaterThanFour将包含单词buffalodinosaur

['buffalo', 'dinosaur']

Apart from findAll(), there are other Groovy methods.

除了findAll()之外,还有其他Groovy方法。

2.3. The collect Iterator

2.3.迭代器 collect

Finally, there is collect, it calls the closure on each item in the collection and returns a new collection with the results of each. Let’s create a new collection out of the sizes of each item in the words collection:

最后,还有collect,它对集合中的每个项目调用闭包,并返回一个包含每个项目结果的新集合。让我们从words集合中的每个项目的大小中创建一个新的集合。

def sizes = words.collect{it.length()}

The result:

其结果是。

[3,7,3,8]

We use sum, as the name suggests to add up all elements in the collection. We can sum up the items in the sizes collection like so:

我们使用sum,顾名思义,将集合中的所有元素相加。我们可以像这样对sizes集合中的项目进行加总。

def charCount = sizes.sum()

and the result will be 21, the character count of all the items in the words collection.

而结果将是21,即words集合中所有项目的字符数。

2.4. The max/min Operators

2.4.最大/最小操作者

The max/min operators are intuitively named to find the maximum or minimum number in a collection :

max/min运算符的直观命名是为了找到一个集合中的最大或最小数。

def maximum = sizes.max()

The result should be obvious, 8.

其结果应该是显而易见的,8。

2.5. The find Iterator

2.5.迭代器 find

We use find to search for only one collection value matching the closure predicate.

我们使用find来搜索只有一个与封闭谓词匹配的集合值。

def greaterThanSeven=sizes.find{it>7}

The result, 8, the first occurrence of the collection item that meets the predicate.

结果,8,符合谓词的集合项的第一次出现。

3. Validate JSON With Groovy

3.用Groovy验证JSON

If we have a service at http://localhost:8080/odds, that returns a list of odds of our favorite football matches, like this:

如果我们在http://localhost:8080/odds有一个服务,它返回我们最喜欢的足球比赛的赔率列表,像这样。

{
    "odds": [{
        "price": 1.30,
        "status": 0,
        "ck": 12.2,
        "name": "1"
    },
    {
        "price": 5.25,
        "status": 1,
        "ck": 13.1,
        "name": "X"
    },
    {
        "price": 2.70,
        "status": 0,
        "ck": 12.2,
        "name": "0"
    },
    {
        "price": 1.20,
        "status": 2,
        "ck": 13.1,
        "name": "2"
    }]
}

And if we want to verify that the odds with a status greater than 1 have prices 1.20 and 5.25, then we do this:

而如果我们想验证状态大于1的赔率的价格1.20和5.25,那么我们这样做。

@Test
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
    get("/odds").then().body("odds.findAll { it.status > 0 }.price",
      hasItems(5.25f, 1.20f));
}

What is happening here is this; we use Groovy syntax to load the JSON array under the key odds. Since it has more than one item, we obtain a Groovy collection. We then invoke the findAll method on this collection.

这里发生的事情是这样的;我们使用Groovy语法来加载键odds下的JSON数组。由于它有一个以上的项目,我们得到一个Groovy集合。然后我们对这个集合调用findAll方法。

The closure predicate tells Groovy to create another collection with JSON objects where status is greater than zero.

封闭谓词告诉Groovy用状态大于0的JSON对象创建另一个集合。

We end our path with price which tells groovy to create another list of only prices of the odds in our previous list of JSON objects. We then apply the hasItems Hamcrest matcher to this list.

我们用price来结束我们的路径,这告诉groovy创建另一个列表,其中只有我们之前的JSON对象列表中的赔率价格。然后我们对这个列表应用hasItems Hamcrest匹配器。

4. Validate XML With Groovy

4.用Groovy验证XML

Let’s assume we have a service at http://localhost:8080/teachers, that returns a list of teachers by their id, department and subjects taught as below:

我们假设在http://localhost:8080/teachers上有一个服务,按iddepartmentsubjects教的教师列表,如下所示。

<teachers>
    <teacher department="science" id=309>
        <subject>math</subject>
        <subject>physics</subject>
    </teacher>
    <teacher department="arts" id=310>
        <subject>political education</subject>
        <subject>english</subject>
    </teacher>
</teachers>

Now we can verify that the science teacher returned in the response teaches both math and physics:

现在我们可以验证,回复中返回的科学老师既教数学又教物理。

@Test
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
    get("/teachers").then().body(
      "teachers.teacher.find { it.@department == 'science' }.subject",
        hasItems("math", "physics"));
}

We have used the XML path teachers.teacher to get a list of teachers by the XML attribute, department. We then call the find method on this list.

我们使用XML路径teachers.teacher来获得一个由XML属性department组成的教师列表。然后我们在这个列表上调用find方法。

Our closure predicate to find ensures we end up with only teachers from the science department. Our XML path terminates at the subject tag.

我们对find的封闭谓词确保我们最终只得到science部门的教师。我们的XML路径终止于subjecttag。

Since there is more than one subject, we will get a list which we validate with the hasItems Hamcrest matcher.

由于有一个以上的主题,我们将得到一个列表,用hasItemsHamcrest匹配器进行验证。

5. Conclusion

5.总结

In this article, we’ve seen how we can use the REST-assured library with the Groovy language.

在这篇文章中,我们已经看到了如何用Groovy语言来使用REST-assured库。

For the full source code of the article, check out our GitHub project.

关于文章的完整源代码,请查看我们的GitHub项目