Menguji API Web dengan Koleksi Tukang Pos

1. Perkenalan

Untuk menguji API web secara menyeluruh, kita membutuhkan semacam klien web untuk mengakses titik akhir API. Postman adalah alat mandiri yang menjalankan API web dengan membuat permintaan HTTP dari luar layanan .

Saat menggunakan Postman, kita tidak perlu menulis kode infrastruktur klien HTTP hanya untuk keperluan pengujian. Sebagai gantinya, kami membuat rangkaian pengujian yang disebut koleksi dan membiarkan Postman berinteraksi dengan API kami.

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

2. Penyiapan

Sebelum kita mulai dengan koleksi kita, kita perlu menyiapkan lingkungan.

2.1. Menginstal Postman

Tukang pos tersedia untuk Linux, Mac, dan Windows. Alat ini dapat diunduh dan diinstal dari situs web Postman.

Setelah menutup layar splash, kita dapat melihat antarmuka pengguna:

2.2. Menjalankan Server

Tukang pos membutuhkan server HTTP langsung untuk memproses permintaannya . Untuk tutorial ini, kita akan menggunakan proyek Baeldung sebelumnya, spring-boot-rest, yang tersedia di GitHub.

Seperti yang bisa kita tebak dari judulnya, spring-boot-rest adalah aplikasi Spring Boot. Kami membangun aplikasi dengan pemasangan sasaran Maven . Setelah dibuat, kami meluncurkan server dengan boot pegas tujuan Maven kustom : run .

Untuk memverifikasi bahwa server sedang berjalan, kita dapat menekan URL ini di browser kita:

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

Layanan ini menggunakan database dalam memori. Semua catatan dihapus saat server dihentikan.

3. Membuat Koleksi Tukang Pos

Koleksi di Postman adalah serangkaian permintaan HTTP. Tukang pos menyimpan setiap aspek permintaan, termasuk header dan badan pesan. Oleh karena itu, kami dapat menjalankan permintaan secara berurutan sebagai pengujian semi-otomatis .

Mari mulai dengan membuat koleksi baru. Kita bisa mengklik panah dropdown pada tombol New dan pilih Collection :

Saat dialog BUAT KOLEKSI BARU muncul, kami dapat menamai koleksi kami " uji API foo ". Terakhir, kami mengklik tombol Buat untuk melihat koleksi baru kami muncul di daftar di sebelah kiri:

Setelah koleksi kami dibuat, kami dapat mengarahkan kursor ke atasnya untuk menampilkan dua tombol menu. Tombol panah membuka panel tarik-kanan yang menyediakan akses ke Collection Runner . Sebaliknya, tombol elipsis membuka menu tarik-turun yang berisi sejumlah operasi pada koleksi.

4. Menambahkan Permintaan POST

4.1. Membuat Permintaan Baru

Sekarang kita memiliki koleksi kosong, mari tambahkan permintaan yang mengenai API kita. Secara khusus, mari kirim pesan POST ke URI / auth / foos. Untuk melakukan itu, kami membuka menu elipsis pada koleksi kami dan memilih Tambah Permintaan.

Saat dialog SIMPAN PERMINTAAN muncul, berikan nama deskriptif, seperti “ tambahkan foo”. Kemudian, klik tombol Save to foo API test .

Setelah permintaan dibuat, kita dapat melihat bahwa koleksi kita menunjukkan satu permintaan . Namun, jika koleksi kami belum diperluas, kami belum dapat melihat permintaan tersebut. Dalam hal ini, kita dapat mengklik koleksi tersebut untuk meluaskannya.

Sekarang, kita akan melihat permintaan baru terdaftar di bawah koleksi kita. Kita dapat mengamati bahwa permintaan baru, secara default, adalah HTTP GET, yang bukan itu yang kita inginkan. Kami akan memperbaikinya di bagian selanjutnya:

4.2. Mengedit Permintaan

Untuk mengedit permintaan, mari kita klik, lalu memuatnya ke tab editor permintaan:

Meskipun editor permintaan memiliki banyak opsi, kami hanya memerlukan beberapa opsi untuk saat ini.

Pertama, mari gunakan dropdown untuk mengubah metode dari GET menjadi POST.

Kedua, kami membutuhkan URL. Di sebelah kanan dropdown metode adalah kotak teks untuk URL permintaan. Jadi, mari kita masukkan sekarang:

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

Langkah terakhir adalah menyediakan badan pesan. Di bawah alamat URL adalah deretan header tab. Kami akan mengklik header tab Body untuk menuju ke editor body.

Di tab Body , tepat di atas area teks, terdapat deretan tombol radio dan dropdown. Ini mengontrol pemformatan dan tipe konten permintaan.

Layanan kami menerima data JSON, jadi kami memilih tombol radio mentah . Dalam dropdown ke kanan, kita menerapkan JSON (aplikasi / json) jenis konten .

Setelah pengkodean dan tipe konten disetel, kami menambahkan konten JSON kami ke area teks:

{ "name": "Transformers" }

Terakhir, pastikan untuk menyimpan perubahan kita dengan menekan Ctrl-S atau menekan tombol Save . The Simpan tombol terletak di sebelah kanan dari Kirim tombol. Setelah kami menyimpan, kami dapat melihat bahwa permintaan telah diperbarui ke POST di daftar di sebelah kiri:

5. Menjalankan Request

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

Pada artikel ini, kami telah menggunakan Postman untuk membuat tes semi-otomatis untuk REST API. Meskipun artikel ini berfungsi sebagai pengantar fitur-fitur dasar Postman, kami hampir tidak menyentuh permukaan kemampuannya. Dokumentasi online Postman adalah sumber daya yang berharga untuk eksplorasi yang lebih dalam.

Koleksi yang dibuat dalam tutorial ini tersedia di GitHub.