https://kotlinlang.org logo
Title
v

Vitali Plagov

03/21/2023, 11:39 AM
I'm writing Playwright tests with Kotlin and I define the Browser and the Page in my BaseTest class to be created before each test. Like this
open class BaseTest {

    lateinit var browser: Browser
    lateinit var page: Page

    @BeforeEach
    fun setUp() {
        browser = Playwright.create().chromium().launch()
        page = browser.newPage()
    }
}
But I don't like to use a mutable
lateinit var
modifiers. How can I turn these two into immutable variables? Using
lazy
? But then the variable will be initialized only once.
s

Sam

03/21/2023, 11:46 AM
Immutable always implies initialized only once. For tests I normally just tolerate
lateinit
variables, even though I wouldn’t use them elsewhere. But an alternative would be to use a higher-order-function to do the test setup, something like this:
class TestSuite {
    private fun withPage(block: (Page) -> Unit) {
        val browser = Playwright.create().chromium().launch()
        val page = browser.newPage()
        block(page)
    }
    
    @Test
    fun myTest() = withPage { page ->
        doStuffWith(page)
    }
}
v

Vitali Plagov

03/21/2023, 12:26 PM
Thank you! Looks interesting. I will consider this!