Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Unit tests in Kotlin, sharing variables?

I am trying to create some functional tests in Kotlin to make requests to a Cart Java service using Rest Assured library.

Since I want the tests to behave procedurally I was hoping I could store the result of the first API request and pass it to the next Unit test.

i.e.

createCartTest() --> cartId --> getCartForWebsiteTest(cartId)

class CartTest : RestAssuredSupport {

    val port = 8080
    val url = "http://localhost:"
    val cartId = null

    /**
     * Create a cart object
     */
    @Test fun createCartTest() {

        given().
                now().
                body("websiteId=1").
                contentType(ContentType.URLENC).
                post(url + port + "/orders/cart/create.do").
                then().
                statusCode(200).
                body("summary.numItems", equalTo(0)).
                body("summary.visibleNumItems", equalTo(0)).
                body("summary.cartId", notNullValue()).
                body("summary.version", notNullValue())
    }

    /**
     * Fetch a cart object created by websiteId and cartId
     */
    @Test fun getCartForWebsite() {

        given().
                now().
                body("websiteId=1&cartId=" + cartId).
                contentType(ContentType.URLENC).
                post(url + port + "/orders/cart/getCartForWebsite.do").
                then().
                statusCode(200).
                body("summary.numItems", equalTo(0)).
                body("summary.visibleNumItems", equalTo(0)).
                body("summary.cartId", equalTo(cartId)).
                body("summary.version", notNullValue())
    }
}

Never really used Kotlin, so looking for advice in what would be the best way to test all the API endpoints are working.

Or would it be better to make another request inside the same function and pass the result to the next step?

What is the best way to share variables across tests?

Thanks

like image 490
tomaytotomato Avatar asked Oct 23 '25 03:10

tomaytotomato


1 Answers

JUnit does not provide any guarantees about the tests ordering, and the tests should not depend on each other nor mutate the shared state.

The easiest solution is, indeed, to perform the two requests in the same test.

Also, you can use JUnit test fixtures to set up the objects you need for a set of tests. If you need the cartId in several tests, that is the preferred option.

class CartTest : RestAssuredSupport {
    // ...
    var cartId: Int by Delegates.notNull()

    @Before fun setUp() {
        // Set up the cartId. This will run before each test. Use @BeforeClass to run once
    }

    @Test fun getCartForWebsite() { /* ... */ }
}

See: Delegates.notNull(), another question about @Before and @BeforeClass.

like image 64
hotkey Avatar answered Oct 25 '25 23:10

hotkey