Running Cypress Tests from JUnit

Let's run the Cypress tests automatically by using JUnit.

To work with Cypress tests, we need to find a way to run them automatically when we build our project. The easiest way is to run them from JUnit with our other automated tests.

Testcontainers

To avoid installing Cypress for running the tests, we’ll use Testcontainers with a Docker image that contains Cypress.

Let’s start by adding two dependencies to the pom.xml:

Press + to interact
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.wimdeblauwe</groupId>
<artifactId>testcontainers-cypress</artifactId>
<version>${testcontainers-cypress.version}</version>
<scope>test</scope>
</dependency>

The org.testcontainers:junit-jupiter dependency allows us to use Testcontainers from JUnit 5. The io.github.wimdeblauwe:testcontainers-cypress dependency allows us to use the Cypress docker image from Testcontainers.

PostgreSQL integration test

We’ll run an integration test that starts PostgreSQL in Docker and the full application locally on a random port:

Press + to interact
package com.tamingthymeleaf.application;
import com.tamingthymeleaf.application.user.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //<.>
@Testcontainers //<.>
public class CypressE2eTests {
@Container //<.>
private static final PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer<>("postgres:12")
.withDatabaseName("tamingthymeleafdb")
.withUsername("user")
.withPassword("secret");
@LocalServerPort //<.>
private int port;
@Autowired
private UserService userService; //<.>
@DynamicPropertySource
static void setup(DynamicPropertyRegistry registry) { //<.>
registry.add("spring.datasource.url", postgresqlContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgresqlContainer::getUsername);
registry.add("spring.datasource.password", postgresqlContainer::getPassword);
}
@BeforeEach
void validatePreconditions() {
assertThat(userService.countUsers()).isZero(); //<.>
}
@Test
void test() {
System.out.println("port = " + port);
System.out.println("Application started");
}
}
  • @SpringBootTest starts the complete application. By setting the webEnvironment to ...