REST Assured in Kotlin

REST Assured is a library for testing HTTP/REST based services on the JVM and version 4.1.0 made this experience even better for Kotlin developers by introducing a new Kotlin API. This blog-post will briefly introduce the new API and hopefully convince you that it’s preferable to the Java API if you’re using Kotlin. But first let’s look at a simple example.

Example Resource

We’re going to keep things simple and just assume we have a webserver running at http://localhost:8080/ that upon receiving a GET to `/users?deleted=false` will return the following JSON response (copied from https://jsonplaceholder.typicode.com/users):

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "email": "Nathan@yesenia.net",
    "address": {
      "street": "Douglas Extension",
      "suite": "Suite 847",
      "city": "McKenziehaven",
      "zipcode": "59590-4157",
      "geo": {
        "lat": "-68.6102",
        "lng": "-47.0653"
      }
    },
    "phone": "1-463-123-4447",
    "website": "ramiro.info",
    "company": {
      "name": "Romaguera-Jacobson",
      "catchPhrase": "Face to face bifurcated interface",
      "bs": "e-enable strategic applications"
    }
  }
]

Validation with the Java API

Now let’s suppose we want to validate a couple of things:

  1. That the status code is equal to 200
  2. That there are 3 users in the list
  3. That one of the users has a name of “Ervin Howell”
  4. The user with username “Samantha” is employed at “Romaguera-Jacobson”

and then we’d like to return the cities of all users. We can do this quite nicely with the Java API:

List cities = 	
given().
		queryParam("deleted", false).
when().
		get("/users").
then().
		statusCode(200).
		body("size()", is(3)).
		body("name.any { it == 'Ervin Howell' }", is(true)).
		body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson")).
extract().
		path("address.city");

While this works fine there are a few annoyances:

Reporting

The first one has to do with the way reporting of validation errors works. Since REST Assured can’t know which body statement that “terminates” the operation it can only perform, and thus report, validations errors one by one. For example if body("size()", is(3)) fails REST Assured cannot continue and check the two remaining statements (body("name.any { it == 'Ervin Howell' }", is(true)) and body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson"))) since it doesn’t know about these statements ahead of time. You’d have to fix the first statement and then re-run the test to know whether or not the subsequent statements pass or not. For this reason REST Assured has a concept called “multi-body expectations” which let’s you define multiple expectations within a single body statement:

List cities = 	
given().
		queryParam("deleted", false).
when().
		get("/users").
then().
		statusCode(200).
		body(
			 "size()", is(3),
			 "name.any { it == 'Ervin Howell' }", is(true),
			 "find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson")
		).
extract().
		path("address.city");

This fixes the problem described above, now all body expectations will be validated in one go and all errors will be reported at once. However if any of the statements preceding the call to body were to fail (statusCode(200) in this case) then body would not be executed since the test has already failed. In a trivial example like this it might not matter all that much, but image a different scenario where you’re also expecting contentType and headers then you can probably tell this is not optimal.

Formatting

Another annoying thing is that the Java DSL doesn’t work well with the default formatting settings in your IDE. If I press cmd+option+l to format the code in Intellij it would look like this:

List cities =
                given().
                        queryParam("deleted", false).
                        when().
                        get("/users").
                        then().
                        statusCode(200).
                        body("size()", is(3)).
                        body("name.any { it == 'Ervin Howell' }", is(true)).
                        body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson")).
                        extract().
                        path("address.city");


Which is much less readable. To work around this I often select the code, press cmd+option+t and then F to disable formatting. Intellij will then insert hints that prevents the code from being formatted in the future:

// @formatter:off
List cities =
given().
		queryParam("deleted", false).
when().
		get("/users").
then().
		statusCode(200).
		body("size()", is(3)).
		body("name.any { it == 'Ervin Howell' }", is(true)).
		body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson")).
extract().
		path("address.city");
// @formatter:on

Validation with the Kotlin API

By adding the Kotlin Extensions Module to the classpath you can start using the API by importing Given from the io.restassured.module.kotlin.extensions package. The test can then be rewritten as:

val cities : List =
Given {
	queryParam("deleted", false)
} When {
	get("/users")
} Then {
	statusCode(200)
	body("size()", is(3))
	body("name.any { it == 'Ervin Howell' }", is(true))
	body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson"))
} Extract {
	path("address.city")
}

It looks similar enough to the Java API but it solves both issues presented earlier. Since the API uses Kotlin’s type-safe builders the formatting problem goes away since Intellij natively understands and formats these builders in a nice way. Also, since all expectations (statusCode and body) are defined inside the Then block, REST Assured can run through all of them in the same go and report all errors at once. This can save you quite a lot of time since you typically use REST Assured for integration testing and the environment (such as Spring) may take some time to boot.

Why capital letters?

You may be wondering why the methods are starting with a capital letter (Given, When, Then etc)? The reason is that when is a reserved keyword in Kotlin and thus it has to be escaped when using it in code (i.e. `when`). To avoid this, the When extension function was introduced. To make things consistent the other methods was thus also named with the first letter capitalized. I’d love the hear some comments on this decision though, does it make sense or not?

Summary

As you’ve seen, the Kotlin API can help to solve two common annoyances that you may experience with the Java API. For this reason, the Kotlin API is recommended for Kotlin users. Any feedback, for example on the naming of methods, is highly appreciated. Thanks for reading!

38 thoughts on “REST Assured in Kotlin

  1. how to add keystore and truststore jks in RestAssured ? ” there is my code but got BadPaddingException, I need help for this issue thanks a lot
    detail
    Caused by: javax.crypto.BadPaddingException: Error finalising cipher data: pad block corrupted
    at org.bouncycastle.jcajce.provider.BaseCipher.engineDoFinal(Unknown Source)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.lambda$engineGetKey$0(PKCS12KeyStore.java:406)
    at java.base/sun.security.pkcs12.PKCS12KeyStore$RetryWithZero.run(PKCS12KeyStore.java:295)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.engineGetKey(PKCS12KeyStore.java:400)
    at java.base/sun.security.util.KeyStoreDelegator.engineGetKey(KeyStoreDelegator.java:90)
    at java.base/java.security.KeyStore.getKey(KeyStore.java:1057)
    at java.base/sun.security.ssl.SunX509KeyManagerImpl.(SunX509KeyManagerImpl.java:145)
    at java.base/sun.security.ssl.KeyManagerFactoryImpl$SunX509.engineInit(KeyManagerFactoryImpl.java:70)
    Code is
    private RestAssured restAssured;
    restAssured; restAssured.config = RestAssured.config().sslConfig(new SSLConfig()
    .trustStore(“truststore.jks”, “password”)
    .keyStore(“keystore.jks”,”password”)
    .keystoreType(“jks”)
    .trustStoreType(“jks”)
    );

  2. На данном сайте можно ознакомиться с информацией о сериале “Однажды в сказке”, его сюжете и ключевых персонажах. однажды в сказке смотреть онлайн бесплатно Здесь представлены интересные материалы о производстве шоу, исполнителях ролей и фактах из-за кулис.

  3. This detailed resource serves as an in-depth guide to the realm of modern video surveillance, offering valuable perspectives for both professional CCTV installers and business owners seeking to enhance their protection systems.
    Internet Software
    The site offers a detailed analysis of cloud-based video surveillance systems, exploring their strengths, drawbacks, and real-world applications.

  4. Здесь публикуются последние новости РФ и всего мира.
    Здесь можно прочитать значимые статьи по разным темам .
    https://ecopies.rftimes.ru/
    Будьте в курсе ключевых событий каждый день .
    Проверенная информация и скорость подачи в каждой публикации .

  5. На этом сайте у вас есть возможность приобрести виртуальные мобильные номера различных операторов. Они могут использоваться для подтверждения профилей в различных сервисах и приложениях.
    В ассортименте представлены как постоянные, так и одноразовые номера, что можно использовать для получения сообщений. Это простое решение для тех, кто не хочет указывать личный номер в интернете.
    виртуальный номер для приема смс
    Процесс покупки максимально простой: выбираете подходящий номер, вносите оплату, и он сразу будет доступен. Попробуйте сервис прямо сейчас!

  6. Центр ментального здоровья — это пространство, где любой может найти помощь и профессиональную консультацию.
    Специалисты работают с различными проблемами, включая стресс, эмоциональное выгорание и депрессивные состояния.
    http://anmay.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Fpreparations%2Ff%2Ffevarin%2F
    В центре применяются современные методы лечения, направленные на восстановление эмоционального баланса.
    Здесь создана безопасная атмосфера для доверительного диалога. Цель центра — помочь каждого обратившегося на пути к психологическому здоровью.

  7. Howdy I am so excited I found your web site, I
    really found you by error, while I was searching on Askjeeve for something
    else, Anyhow I am here now and would just like to say thank you
    for a tremendous post and a all round thrilling blog (I also
    love the theme/design), I don’t have time to go through it
    all at the moment but I have saved it and also added your RSS
    feeds, so when I have time I will be back to read a great deal more, Please do keep up the fantastic job.

    Here is my webpage: brians club bins

  8. Thanks for the marvelous posting! I certainly
    enjoyed reading it, you can be a great author.I
    will always bookmark your blog and may come back down the
    road. I want to encourage continue your great posts, have a nice morning!

    My website … bryan club

  9. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.

    nonetheless, you command get got an edginess over that you wish be delivering
    the following. unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this hike.

    Visit my page: order cvv on briansclub

  10. Have you ever thought about writing an e-book or guest authoring on other blogs?
    I have a blog based upon on the same ideas you discuss and would love to have you share some stories/information. I know my visitors
    would enjoy your work. If you are even remotely interested, feel
    free to shoot me an email.

    Also visit my site :: bidencash leaks

  11. Great goods from you, man. I’ve understand your stuff previous to and you are just too fantastic.
    I actually like what you have acquired here, really like what
    you’re saying and the way in which you say it. You
    make it entertaining and you still care for to keep it wise.
    I can not wait to read far more from you. This is actually a wonderful web site.

    Look into my blog post :: xleet.wp

  12. What i don’t realize is in reality how you are no longer really
    a lot more neatly-favored than you may be right
    now. You’re very intelligent. You know therefore considerably with regards to this topic, made me in my opinion imagine it
    from a lot of various angles. Its like women and men are not involved unless it is one
    thing to accomplish with Woman gaga! Your individual stuffs
    great. All the time deal with it up!

    Look into my blog … stashpatricks cc

  13. Heya i’m for the first time here. I found this board and I in finding It truly useful & it helped me out much.
    I’m hoping to present one thing back and aid others such as you
    helped me.

    Also visit my web blog; pro kill

  14. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  15. На этом сайте вы найдете всю информацию о ментальном здоровье и его поддержке.
    Мы рассказываем о методах развития эмоционального равновесия и борьбы со стрессом.
    Экспертные материалы и советы экспертов помогут разобраться, как поддерживать психологическую стабильность.
    Важные темы раскрыты доступным языком, чтобы любой мог получить важную информацию.
    Начните заботиться о своем душевном здоровье уже прямо сейчас!
    lehighvalleyhospital.com

  16. Центр “Эмпатия” предлагает комплексную помощь в области ментального благополучия.
    Здесь принимают опытные психологи и психотерапевты, готовые помочь в сложных ситуациях.
    В “Эмпатии” применяют современные методики терапии и персональные программы.
    Центр помогает при депрессии, тревожных расстройствах и других проблемах.
    Если вы нуждаетесь в комфортное место для решения личных вопросов, “Эмпатия” — верное решение.
    wiki.dominerbusiness.com

  17. Today, I went to the beachfront with my children. I found a sea shell
    and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear.

    She never wants to go back! LoL I know this
    is completely off topic but I had to tell someone! http://www.onestopclean.kr/bbs/board.php?bo_table=free&wr_id=968330

  18. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  19. Клиника премиум-класса предлагает высококачественные медицинские услуги в любых возрастных категориях.
    Мы гарантируем индивидуальный подход и заботу о вашем здоровье.
    В клинике работают опытные и внимательные врачи, использующие передовые методики.
    Наши услуги включают широкий спектр медицинских процедур, в том числе консультации специалистов.
    Ваш комфорт и безопасность — важнейшая задача нашего коллектива.
    Обратитесь к нам, и мы поможем вам вернуться к здоровой жизни.
    branding.magetique.com

Leave a Reply to Binance创建账户 Cancel reply

Your email address will not be published. Required fields are marked *