How to test Spring views using Playwright and SpringBootTest in Kotlin and Java
Tags: java, selenium, playwright, springboot
Published: 2023-10-25 00:08:50

In today's agile development landscape, testing your web application thoroughly is more important than ever. A toolset that facilitates quick and reliable testing can be a developer's best friend. This is where integrating Playwright, a powerful browser automation library, with your SpringBoot application comes into play.

In this blog post, we delve deep into how you can leverage the capabilities of Playwright browsers to write robust tests for your SpringBoot HTML endpoints. Whether you are a seasoned developer or just getting started with SpringBoot, this guide will walk you through the steps to test your Spring views seamlessly using Playwright and the SpringBootTest annotation.

Get ready to enhance the stability and reliability of your web application by integrating the prowess of Playwright into your testing regimen.

## What is Playwright?

Playwright is a tool from Microsoft that enables browser automation and testing. Java developers can utilize Playwright to script multi-browser tests with a modern and fluent API design, enjoying perks like automatic waiting, efficient selectors, and seamless handling of iframes and pop-ups, which can notably reduce the flakiness often associated with browser tests.

### Why no Selenium
In comparison, Selenium, a well-established tool in the Java world, might be familiar ground for many developers, offering wide-ranging browser support and a vast array of community-driven plugins and integrations. However, it sometimes falls short in speed and requires more boilerplate code, making tests less concise.

### Manual testing
Furthermore, when we bring manual testing into the picture, the advantages of tools like Playwright become even more apparent. Manual testing, although necessary in certain contexts, can be time-consuming and prone to human error. Automating your testing process with Playwright not only expedites the testing cycle but also ensures a higher degree of accuracy and reliability, fostering a more agile and responsive development workflow. Thus, Playwright stands as a modern alternative that can complement or even replace Selenium and manual testing methodologies, pushing towards a more streamlined and efficient testing approach in the Java ecosystem.

## Writing a test
In this post we will test an endpoint that renders HTML forms. We will use SpringBootTest and Playwright to load the page and make assertions.

### Spring boot setup
Assuming you have an existing Spring boot application, create a test file. Our initial scaffold will look like this. **Note** we are using Kotlin in this post but you can use Java without any problems.

```kotlin
package browser

import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension


@ExtendWith(SpringExtension::class)
@SpringBootTest(
      webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@UseEmbeddedPostgres
class AdminBrowserTest {
    @LocalServerPort
    private int port;
}
```

We use a `RANDOM_PORT` environment here so we can map the server's port using `@LocalServerPort`. This will come in handy when we want to load the server pages in Playwright.


### Installing Playwright

For maven users add this to your `pom.xml`:

```xml
<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.37.0</version>
    </dependency>
</dependencies>
```

For gradle add the `testImplementation`:

```
repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'com.microsoft.playwright:playwright:1.37.0'
}
```

### Adding Playwright
Next we can import Playwright and AssertJ into our tests:

```
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.assertj.core.api.Assertions.assertThat
```

Now we can create a playwright browser instance for each test case:

```kotlin
companion object {
    // Shared between all tests in this class.
    var playwright: Playwright? = null
    var browser: Browser? = null

    // New instance for each test method.
    var context: BrowserContext? = null
    var page: Page? = null

    @JvmStatic
    @BeforeAll
    fun launchBrowser() {
        playwright = Playwright.create()
        browser = playwright!!.chromium().launch()
    }

    @AfterAll
    @JvmStatic
    fun closeBrowser() {
        playwright!!.close()
    }
}

@BeforeEach
fun createContextAndPage() {
    context = browser.newContext()
    page = context.newPage()
}

@AfterEach
fun closeContext() {
    context.close()
}

@Test
fun `can load index` () {
    page.navigate("http://localhost:$port")
    assertThat(page.waitForSelector("h1").innerText()).contains("MailSlurp")
}
```

## Conclusion
In conclusion, integrating Playwright as a testing tool for your Spring Boot application in Java offers practical benefits. Playwright facilitates a straightforward and effective testing process, allowing for easy automation of browser actions, which can be a substantial time-saver compared to manual testing methods. Its modern API design enables concise and maintainable test scripts, which can potentially simplify the codebase and reduce maintenance efforts.

Compared to other testing tools like Selenium, Playwright often offers faster execution times and more reliable test runs, helping to speed up the development cycle without sacrificing quality. Its compatibility with Spring Boot ensures that developers can leverage its features without any significant adjustments to their existing setups.

Overall, incorporating Playwright into your Spring Boot project represents a logical step towards enhancing the efficiency and reliability of your application's testing procedures, making it a valuable addition to your Java project's testing toolkit.

## Extending tests with email
In automated testing, ensuring the correct functioning of email services within your application is crucial. Combining Playwright with the MailSlurp Java client can streamline this process remarkably.

With MailSlurp, you can create and manage email addresses dynamically to send and receive emails during your tests, allowing for real-time verification of email functionalities within your application.

Meanwhile, Playwright can be used to automate browser interactions, including actions triggered by received emails, such as clicking verification links or resetting passwords.

Together, Playwright and MailSlurp can work in harmony to create a comprehensive testing environment where both web interactions and email communications can be tested seamlessly and effectively, enhancing the reliability and robustness of your application.