Menguji API Web dengan Koleksi Postman

1. Pengenalan

Untuk menguji API web secara menyeluruh, kami memerlukan beberapa jenis klien web untuk mengakses titik akhir API. Postman adalah alat mandiri yang menggunakan API web dengan membuat permintaan HTTP dari luar perkhidmatan .

Semasa menggunakan Postman, kami tidak perlu menulis kod infrastruktur klien HTTP hanya untuk pengujian. Sebagai gantinya, kami membuat suite ujian yang disebut koleksi dan membiarkan Postman berinteraksi dengan API kami.

Dalam tutorial ini, kita akan melihat cara membuat Koleksi Postman yang dapat menguji REST API.

2. Persediaan

Sebelum memulakan koleksi kami, kami perlu mengatur persekitarannya.

2.1. Memasang Postman

Postman tersedia untuk Linux, Mac, dan Windows. Alat ini boleh dimuat turun dan dipasang dari laman web Postman.

Setelah menutup skrin percikan, kita dapat melihat antara muka pengguna:

2.2. Menjalankan Pelayan

Postman memerlukan pelayan HTTP langsung untuk memproses permintaannya . Untuk tutorial ini, kami akan menggunakan projek Baeldung sebelumnya, spring-boot-rest, yang terdapat di GitHub.

Seperti yang kita duga dari tajuknya, spring-boot-rest adalah aplikasi Spring Boot. Kami membina aplikasi dengan pemasangan tujuan Maven . Setelah dibina, kami melancarkan pelayan dengan Maven tujuan spring-boot: run .

Untuk mengesahkan bahawa pelayan sedang berjalan, kami dapat menekan URL ini di penyemak imbas kami:

//localhost:8082/spring-boot-rest/auth/foos

Perkhidmatan ini menggunakan pangkalan data dalam memori. Semua rekod dihapus semasa pelayan dihentikan.

3. Membuat Koleksi Posmen

Koleksi di Postman adalah rangkaian permintaan HTTP. Postman menyimpan setiap aspek permintaan, termasuk tajuk dan badan mesej. Oleh itu, kami dapat menjalankan permintaan secara berurutan sebagai ujian separa automatik .

Mari mulakan dengan membuat koleksi baru. Kita boleh mengklik anak panah dropdown pada butang Baru dan memilih Koleksi :

Apabila dialog CREATE A NEW COLLECTION muncul, kami dapat menamakan koleksi kami sebagai " ujian API foo ". Akhirnya, kami mengklik butang Buat untuk melihat koleksi baru kami muncul dalam senarai di sebelah kiri:

Setelah koleksi kami dibuat, kami dapat mengarahkan kursor ke atasnya untuk menunjukkan dua butang menu. Butang anak panah membuka panel tarik-kanan yang menyediakan akses ke Collection Runner . Sebaliknya, butang elips membuka menu dropdown yang mengandungi sejumlah operasi pada koleksi.

4. Menambah Permintaan POST

4.1. Membuat Permintaan Baru

Sekarang kami mempunyai koleksi kosong, mari tambahkan permintaan yang memenuhi API kami. Secara khusus, mari kita hantar mesej POST ke URI / auth / foos. Untuk melakukan itu, kami membuka menu elips pada koleksi kami dan pilih Tambah Permintaan.

Apabila dialog SAVE REQUEST muncul, mari berikan nama deskriptif, seperti " tambahkan foo". Kemudian, klik butang Save to foo API test .

Setelah permintaan dibuat, kami dapat melihat bahawa koleksi kami menunjukkan satu permintaan . Namun, jika koleksi kami belum diperluas, kami belum dapat melihat permintaannya. Sekiranya demikian, kita boleh mengklik koleksi untuk mengembangkannya.

Sekarang, kita mesti melihat permintaan baru yang disenaraikan di bawah koleksi kami. Kita dapat melihat bahawa permintaan baru, secara lalai, adalah HTTP GET, yang tidak seperti yang kita mahukan. Kami akan memperbaikinya di bahagian seterusnya:

4.2. Mengedit Permintaan

Untuk mengedit permintaan, mari klik, dengan itu memuatkannya ke tab editor permintaan:

Walaupun editor permintaan mempunyai banyak pilihan, kami hanya memerlukan beberapa daripadanya sekarang.

Pertama, mari gunakan dropdown untuk menukar kaedah dari GET ke POST.

Kedua, kita memerlukan URL. Di sebelah kanan dropdown kaedah adalah kotak teks untuk URL permintaan. Oleh itu, mari kita masukkan sekarang:

//localhost:8082/spring-boot-rest/auth/foos

Langkah terakhir adalah menyediakan badan mesej. Di bawah alamat URL terdapat deretan tajuk tajuk. Kami akan mengklik tajuk tab Badan untuk pergi ke penyunting badan.

Di tab Badan , tepat di atas kawasan teks, terdapat deretan butang radio dan dropdown. Ini mengawal format dan jenis kandungan permintaan.

Perkhidmatan kami menerima data JSON, jadi kami memilih butang radio mentah . Di menu lungsur di sebelah kanan, kami menggunakan jenis kandungan JSON (application / json) .

Setelah pengekodan dan jenis kandungan telah ditetapkan, kami menambahkan kandungan JSON kami ke kawasan teks:

{ "name": "Transformers" }

Akhirnya, pastikan untuk menyimpan perubahan kami dengan menekan Ctrl-S atau menekan butang Simpan . The Simpan butang terletak di sebelah kanan Hantar butang. Setelah menyimpan, kita dapat melihat bahawa permintaan telah dikemas kini ke POST dalam senarai di sebelah kiri:

5. Menjalankan Permintaan

5.1. Menjalankan Permintaan Tunggal

To run a single request, we just click the Send button to the right of the URL address. Once we click Send, the response panel will open below the request panel. It may be necessary to scroll down to see it:

Let's examine our results. Specifically, in the header bar, we see that our request succeeded with the status 201 Created. Furthermore, the response body shows that our Transformers record received an id of 1.

5.2. Using the Collection Runner

In contrast to the Send button, the collection runner can execute an entire collection. To launch the collection runner, we hover the cursor over our foo API test collection and click the pull-right arrow. In the pull-right panel we can see a Run button, so let's click that:

When we click the Run button the collection runner opens in a new window. Because we launched it from our collection, the runner is already initialized to our collection:

The collection runner offers options that affect the test run, but we won't need them for this exercise. Let's go directly to the Run foo API test button at the bottom and click that.

When we run the collection, the view changes to Run Results. In this view, we see a list of tests that are marked green for success and red for failure.

Even though our request was sent, the runner indicates that zero tests passed and zero tests failed. This is because we haven't added tests to our request yet:

6. Testing the Response

6.1. Adding Tests to a Request

To create a test, let's return to the request editing panel where we built our POST method. We click the Tests tab which is located under the URL. When we do that, the Tests panel appears:

In the Tests panel, we write JavaScript that will be executed when the response is received from the server.

Postman offers built-in variables that provide access to the request and response. Furthermore, a number of JavaScript libraries can be imported using the require() syntax.

There are far too many scripting features to cover in this tutorial. However, the official Postman documentation is an excellent resource on this topic.

Let's continue by adding three tests to our request:

pm.test("success status", () => pm.response.to.be.success ); pm.test("name is correct", () => pm.expect(pm.response.json().name).to.equal("Transformers")); pm.test("id was assigned", () => pm.expect(pm.response.json().id).to.be.not.null );

As we can see, these tests make use of the global pm module provided by Postman. In particular, the tests use pm.test(), pm.expect(), and pm.response.

The pm.test() function accepts a label and an assertion function, such as expect(). We're using pm.expect() to assert conditions on the contents of the response JSON.

The pm.response object provides access to various properties and operations on the response returned from the server. Available properties include the response status and JSON content, among others.

As always, we save our changes with Ctrl-S or the Save button.

6.2. Running the Tests

Now that we have our tests, let's run the request again. Pressing the Send button displays the results in the Test Results tab of the response panel:

Likewise, the collection runner now displays our test results. Specifically, the summary at the top left shows the updated passed and failed totals. Below the summary is a list that shows each test with its status:

6.3. Viewing the Postman Console

The Postman Console is a useful tool for creating and debugging scripts. We can find the console under the View menu with the item name Show Postman Console. When launched, the console opens in a new window.

While the console is open, it records all HTTP requests and responses. Furthermore, when scripts use console.log(), the Postman Console displays those messages:

7. Creating a Sequence of Requests

So far, we've focused on a single HTTP request. Now, let's see what we can do with multiple requests. By chaining together a series of requests, we can simulate and test a client-server workflow.

In this section, let's apply what we've learned in order to create a sequence of requests. Specifically, we'll add three more requests to execute after the POST request we have already created. These will be a GET, a DELETE, and finally, another GET.

7.1. Capturing Response Values in Variables

Before we create our new requests, let's make a modification to our existing POST request. Because we don't know which id the server will assign each foo instance, we can use a variable to capture the id returned by the server.

To capture that id, we'll add one more line to the end of the POST request's test script:

pm.variables.set("id", pm.response.json().id);

The pm.variables.set() function takes a value and assigns it to a temporary variable. In this case, we're creating an id variable to store our object's id value. Once set, we can access this variable in later requests.

7.2. Adding a GET Request

Now, using the techniques from previous sections, let's add a GET request after the POST request.

With this GET request, we'll retrieve the same foo instance that the POST request created. Let's name this GET request as “get a foo“.

The URL of the GET request is:

//localhost:8082/spring-boot-rest/auth/foos/{{id}}

In this URL, we're referencing the id variable that we previously set during the POST request. Thus, the GET request should retrieve the same instance that was created by the POST.

Variables, when appearing outside of scripts, are referenced using the double-brace syntax {{id}}.

Since there's no body for a GET request, let's proceed directly to the Tests tab. Because the tests are similar, we can copy the tests from the POST request, then make a few changes.

Firstly, we don't need to set the id variable again, so let's not copy that line.

Secondly, we know which id to expect this time, so let's verify that id. We can use the id variable to do that:

pm.test("success status", () => pm.response.to.be.success ); pm.test("name is correct", () => pm.expect(pm.response.json().name).to.equal("Transformers")); pm.test("id is correct", () => pm.expect(pm.response.json().id).to.equal(pm.variables.get("id")) );

Since the double-brace syntax is not valid JavaScript, we use the pm.variables.get() function to access the id variable.

Finally, let's save the changes as we've done before.

7.3. Adding a DELETE Request

Next, we'll add a DELETE request that will remove the foo object from the server.

We'll proceed by adding a new request after the GET, and setting its method to DELETE. We can name this request “delete a foo“.

The URL of the delete is identical to the GET URL:

//localhost:8082/spring-boot-rest/auth/foos/{{id}}

The response will not have a body to test, but we can test the response code. Therefore, the DELETE request will have only one test:

pm.test("success status", () => pm.response.to.be.success );

7.4. Verifying the DELETE

Finally, let's add another copy of the GET request to verify that the DELETE really worked. This time, let's duplicate our first GET request instead of creating a request from scratch.

To duplicate a request, we right-click on the request to show the dropdown menu. Then, we select Duplicate.

The duplicate request will have the word Copy appended to its name. Let's rename it to “verify delete” to avoid confusion. The Rename option is available by right-clicking the request.

By default, the duplicate request appears immediately after the original request. As a result, we'll need to drag it below the DELETE request.

The final step is to modify the tests. However, before we do that, let's take an opportunity to see a failed test.

We have copied the GET request and moved it after the DELETE, but we haven't updated the tests yet. Since the DELETE request should have deleted the object, the tests should fail.

Let's make sure to save all of our requests, then hit Retry in the collection runner. As expected, our tests have failed:

Now that our brief detour is complete, let's fix the tests.

By reviewing the failed tests, we can see that the server responds with a 500 status. Therefore, we'll change the status in our test.

Furthermore, by viewing the failed response in the Postman Console, we learn that the response includes a cause property. Moreover, the cause property contains the string “No value present“. We can test for that as well:

pm.test("status is 500", () => pm.response.to.have.status(500) ); pm.test("no value present", () => pm.expect(pm.response.json().cause).to.equal("No value present"));

7.5. Running the Full Collection

Now that we've added all of the requests, let's run the full collection in the collection runner:

If everything has gone according to plan, we should have nine successful tests.

8. Exporting and Importing the Collection

While Postman stores our collections in a private, local location, we may want to share the collection. To do that, we export the collection to a JSON file.

The Export command is available within the ellipsis menu of the collection. When prompted for a JSON file version, let's choose the latest recommended version.

After we select the file version, Postman will prompt for a file name and location for the exported collection. We can choose a folder within our GitHub project, for example.

To import a previously exported collection, we use the Import button. We can find it in the toolbar of the main Postman window. When Postman prompts for a file location, we can navigate to the JSON file we wish to import.

It's worth noting that Postman does not track exported files. As a result, Postman doesn't show external changes until we re-import the collection.

9. Conclusion

Dalam artikel ini, kami telah menggunakan Postman untuk membuat ujian separa automatik untuk REST API. Walaupun artikel ini berfungsi sebagai pengenalan kepada ciri-ciri asas Postman, kami hampir tidak mencakar permukaan kemampuannya. Dokumentasi dalam talian Postman adalah sumber yang berharga untuk penerokaan yang lebih mendalam.

Koleksi yang dibuat dalam tutorial ini boleh didapati di GitHub.