Exercise 3: Mutation Testing with Pitest & End-to-End Testing with Playwright
In this exercise, you will explore advanced software verification techniques at two opposite ends of the testing pyramid: Mutation Testing (evaluating test suite thoroughness at the unit and integration level) and End-to-End (E2E) Testing (verifying functional user journeys across the browser and application stack).
Mutation testing evaluates the fault-detection capability of your test suite by injecting deliberate artificial faults (mutants) into your bytecode and observing whether your tests fail (kill the mutant). Meanwhile, End-to-End testing validates that the entire integrated application—from HTTP routing and database persistence to HTML rendering and client-side interactions—functions correctly from the perspective of an end user driving a real web browser.
You will work with a fork of the Spring Petclinic web application (branch csui).
Unlike the REST-only API variant used in Exercises 1 and 2,
this project provides a full server-rendered web UI built with Spring MVC and Thymeleaf templates.
Make sure you are not continuing the spring-petclinic-rest codebase!
Getting Started
Complete the following prerequisites before starting the exercise:
- Ensure you are enrolled in the SQA (PMPL) course and have an active account on GitLab CSUI.
- Verify that the required development tools are installed on your workstation:
- Git
- Java JDK version 17
- Node.js (optional, recommended for launching Playwright Trace Viewer via
npx) - Modern terminal environment and IDE (IntelliJ IDEA, VS Code, etc.)
- Open the Spring Petclinic project on GitLab CSUI and fork it into your personal namespace.
- Clone your fork locally and switch to the
csuibranch:1 2 3 4
git clone git@gitlab.cs.ui.ac.id:<YOUR_USERNAME>/spring-petclinic.git cd spring-petclinic git switch csui git pull origin csui - Create a new working branch for this exercise:
1git switch -c task/3-mutation-and-e2e - Verify that the existing unit and integration test suite compiles and runs cleanly:
1./mvnw clean test
Part 1: Mutation Testing with Pitest
Task 1: Configure Pitest
Pitest is the state-of-the-art mutation testing system for Java and the JVM.
To integrate Pitest into Spring Petclinic, configure the Pitest Maven Plugin in pom.xml.
-
Open
pom.xmland locate the<properties>block. Add the properties for Pitest plugin version, JUnit 5 plugin dependency, and mutation engine:1 2 3 4 5 6
<properties> <!-- ... existing properties ... --> <maven.pitest-plugin.version>1.20.3</maven.pitest-plugin.version> <maven.pitest-junit5-plugin.version>1.2.3</maven.pitest-junit5-plugin.version> <pitest.mutationEngine>gregor</pitest.mutationEngine> </properties> -
Locate the
<build><plugins>section inpom.xml. Add thepitest-mavenplugin configuration:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<plugin> <groupId>org.pitest</groupId> <artifactId>pitest-maven</artifactId> <version>${maven.pitest-plugin.version}</version> <configuration> <mutationEngine>${pitest.mutationEngine}</mutationEngine> <timestampedReports>false</timestampedReports> <targetClasses> <!-- Mandatory classes to analyse --> <param>org.springframework.samples.petclinic.owner*</param> <!-- You can add more classes to analyse by adding more <param> element E.g., <param>org.springframework.samples.petclinic.vet*</param> to analyse classes in vet package --> </targetClasses> </configuration> <dependencies> <dependency> <groupId>org.pitest</groupId> <artifactId>pitest-junit5-plugin</artifactId> <version>${maven.pitest-junit5-plugin.version}</version> </dependency> </dependencies> </plugin> -
Commit your configuration change to git:
1 2
git add pom.xml git commit -m "Configure pitest-maven plugin"
Task 2: Run Pitest and Generate the Mutation Report
With Pitest configured, execute mutation coverage analysis using the Maven wrapper:
-
Run the following command from the repository root:
1./mvnw test-compile org.pitest:pitest-maven:mutationCoverageNote:
test-compileMaven task ensures that test and production classes are compiled and up to date before Pitest runs the mutation goal. -
Once the execution completes, open the generated HTML report in your browser. You will see metrics that we covered in the lectures, such as line coverage, mutation coverage, and test strength.
- Remember the RIPR model we covered in earlier lectures to reason about why mutants survive:
- Reachability: The test must execute the mutated statement.
- Infection: The mutated statement must produce an erroneous internal state.
- Propagation: The erroneous state must propagate to an observable program state (e.g., return value or thrown exception).
- Revealability: The test assertion must inspect and detect the incorrect state.
Task 3: Guided Mutant Analysis
Examine the report for org.springframework.samples.petclinic.owner.OwnerController.
Notice a surviving mutant generated by MathMutator at line 144 of OwnerController.java inside findPaginatedForOwnersLastName:
1 2 3 4 5 6 7 | |
The MathMutator replaced validatedPage - 1 with validatedPage + 1.
Under this mutant, requesting page 1 causes the controller to request page 2 (0-indexed page index 2) from the repository rather than page 0.
Look at the tests covering this method in OwnerControllerTests.java and PetClinicIntegrationTests.java.
There are two issues with the tests at it current version:
- In
OwnerControllerTests, repository interactions are stubbed with Mockito:Notice the argument matcher:1when(this.owners.findByLastNameStartingWith(anyString(), any(Pageable.class))).thenReturn(tasks);any(Pageable.class). Because Mockito accepts anyPageableinstance regardless of its page number or size, it returnstaskswhethervalidatedPage - 1orvalidatedPage + 1was passed. The infection inpageablenever affects the mock's return value! - In
PetClinicIntegrationTests.java, theownerList()test checks:The test only checks that the HTTP status code is1 2 3 4 5 6
@Test void ownerList() { RestTemplate template = builder.baseUri("http://localhost:" + port).build(); ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners?lastName=").build(), String.class); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); }200 OK. It does not assert which page of owners is rendered in the HTML view.
To kill this mutant, we must strengthen our test assertions so that an incorrect Pageable argument causes test failure.
Open src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java.
Then, specify the expected PageRequest directly in verify() or when():
1 2 3 4 | |
After updated the tests, rerun Pitest:
1 | |
Reopen target/pit-reports/index.html and verify that the MathMutator at line 144 in OwnerController.java is now KILLED.
Commit your changes:
1 2 | |
Task 4: DIY Mutant Analysis & Elimination
Now it is your turn to independently analyse and kill a surviving mutant.
Open the Pitest report and inspect org.springframework.samples.petclinic.owner.Owner.
Then, take a look around lines 178-183:
1 2 3 4 5 6 7 8 9 10 | |
There is a surviving mutant that was produced by VoidMethodCallMutator mutation operator,
which removes the calls to Assert.notNull() statements.
The survival reason should be pretty obvious. If you check the existing test cases,
there are no test cases that attempted to pass null or non-existing pet to the SUT.
Therefore, your task is to add unit tests that provide null inputs and invalid pet IDs to kill the mutants.
Part 2: End-to-End (E2E) Testing with Playwright
Take a look at the following code snippets that use mock test from the Spring Petclinic codebase:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Unit and integration tests verify components within isolated mock environments (such as Spring's MockMvc).
From the example above, developers can verify the behaviour of the controller component without deploying the entire application on a runtime environment.
While fast and informative, mock tests cannot detect issues stemming from real browser engines, dynamic HTML/CSS rendering, form submission workflows, or browser-level navigation.
End-to-End (E2E) testing verifies the application by controlling a headless or headful web browser instance that interacts with the live application. There are three commonly mentioned browser automation framework, such as Selenium, Cypress, and Playwright. In this exercise, we will use Playwright, which is maintained by Microsoft. Playwright provides the following:
- Multi-browser support (Chromium, Firefox, WebKit).
- Automatic waiting (no arbitrary
Thread.sleepor polling loops). - Resilient locators prioritising accessibility (ARIA roles, labels, text) over brittle XPath or CSS selectors.
- Comprehensive debugging tools, including the interactive Playwright Trace Viewer.
Task 1: Configure Playwright Java in Maven & Base Test Architecture
In this task, you will add the Playwright Java dependency to your pom.xml and construct an abstract base test class that boots the Spring Boot application on a dynamic port and sets up Playwright's JUnit 5 extension.
1. Add Playwright Dependency
Open pom.xml and add com.microsoft.playwright:playwright inside the <dependencies> block:
1 2 3 4 5 6 | |
2. Create Base E2E Test Class
Create a base class named AbstractPetClinicE2ETests under src/test/java/org/springframework/samples/petclinic/e2e/AbstractPetClinicE2ETests.java.
This class serves two purposes:
- It boots the Spring Boot application on a random available port using
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT). - It activates the official Playwright JUnit 5 extension via
@UsePlaywright, providing dependency injection of Playwright fixtures (Page,BrowserContext, etc.) directly into test methods, configured to run headless and record traces on failure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
Task 2: Baseline Smoke Test
Before writing complex multi-page interactions, create a smoke test to verify automated browser launch and basic elements in the home page.
Create PetClinicSmokeE2ETests.java under src/test/java/org/springframework/samples/petclinic/e2e/:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Run the smoke test:
1 | |
Confirm that the test suite boots Spring Boot, opens Chromium headlessly, and passes all assertions.
Task 3: Implement Page Object Model (POM) Pattern
Writing raw locator calls (page.locator(...), page.getByRole(...)) directly inside test methods leads to code duplication and high maintenance cost whenever the UI templates change.
The Page Object Model (POM) is a design pattern that abstracts web pages into reusable Java classes. Each Page Object encapsulates the page's HTML structure, locators, and actions. Test classes interact only with the high-level methods of Page Objects.
1. Locator Strategy
If you have read the XPath section in BDD workshop, it shows a challenge in locating an element in a client-side rendered page produced by library such as React or Angular. Locating an element can be done using an inspector tool provided by the browser, then obtain the XPath expression to be given to a locator function provided by browser automation framework.
However, XPath could be not stable. Especially in a client-side rendered pages where HTML elements could be updated dynamically. Instead of using XPath, modern browser automation framework such as Playwright encourages using user-facing locators reflecting how users and assistive technologies perceive the page, rather than brittle implementation details like CSS classes or internal DOM IDs.
The following is a table summarises the locator strategies, which generated by generative AI (Gemini 4 Hydrogen):
| Strategy | Playwright API | Why Prefer? |
|---|---|---|
| Role (ARIA) | page.getByRole(AriaRole.BUTTON, ...) |
Matches semantic elements (<button>, <a>, <input type="submit">), enforcing accessibility standards. |
| Label | page.getByLabel("Last name") |
Pairs form inputs with their corresponding <label>, resilient against ID changes. |
| Text | page.getByText("Owner Information") |
Matches visible text content displayed to users. |
| CSS / XPath | page.locator(".btn.btn-primary") |
Avoid unless necessary: brittle; frequently breaks during styling refactors. |
2. Implement FindOwnersPage
Create FindOwnersPage.java in package org.springframework.samples.petclinic.e2e.pages:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
3. Implement OwnerInformationPage
Create OwnerInformationPage.java in package org.springframework.samples.petclinic.e2e.pages:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
4. Implement Search Flow Tests
In Spring Petclinic, searching for owners exhibits two distinct navigational behaviours:
- Single result: Searching for a last name matching exactly one owner (e.g.,
Franklin) immediately redirects to/owners/{id}. - Multiple results: Searching for a last name shared by multiple owners (e.g.,
Davis, matching Betty Davis and Harold Davis) renders a selection table (owners/ownersList.html).
Create FindOwnersE2ETests.java under src/test/java/org/springframework/samples/petclinic/e2e/:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
Execute both tests:
1 | |
Task 4: Trace Viewer Diagnostics
When an E2E test fails in a headless CI/CD environment, standard console logs often do not provide sufficient context to determine why an element was not visible or why a redirect failed.
Playwright's Trace Viewer records a holistic diagnostic bundle for each test run:
- Action-by-action timeline with step durations.
- Visual before/after snapshots of the DOM at each action.
- Live DOM tree inspector with computed styles and locator pickers.
- Console logs, network requests, responses, and execution stack traces.
1. Trace Retention Configuration
In Task 5, we configured AbstractPetClinicE2ETests with:
1 2 | |
With RETAIN_ON_FAILURE, Playwright records traces in memory during test execution.
If the test passes, the trace is discarded, avoiding unnecessary disk consumption.
If any assertion fails or an unhandled exception occurs, Playwright dumps a .zip trace archive to target/playwright-traces/.
You can also record all traces from successful and failing tests by setting Options.Trace.ON to the setTrace configuration call.
But be careful when doing so in a project with large number of E2E tests.
It will produce large number of traces, which in turn contain screenshots of the app.
2. Try to Run a Diagnostic Trace Experiment
To observe and inspect trace output:
- Temporarily introduce an intentional failure into
testSearchSingleOwnerRedirect, for example:1assertEquals("Incorrect Name", ownerPage.getOwnerName()); - Run the test:
1./mvnw test -Dtest=FindOwnersE2ETests - Check the
target/playwright-traces/directory. You will find a newly generated zip file containing the recorded trace. - Open the Trace Viewer on trace.playwright.dev and upload the
.zipfile. Alternatively, if you have Node.js toolchain installed, you can also run the Trace Viewer locally:
1 | |
Task 5: DIY - Owner Registration & Pet Creation
In this hands-on task, you will independently design two new Page Objects and write a complete E2E user journey test:
- Design
AddOwnerPageundersrc/test/java/org/springframework/samples/petclinic/e2e/pages/AddOwnerPage.java:- Represents the form at
/owners/new. - Encapsulates locators and filling actions for:
First NameLast NameAddressCityTelephone- Submit button (
Add Owner)
- Prioritise accessible locators (
getByLabel(...),getByRole(...)).
- Represents the form at
- Design
AddPetPageundersrc/test/java/org/springframework/samples/petclinic/e2e/pages/AddPetPage.java:- Represents the form at
/owners/{ownerId}/pets/new. - Encapsulates locators and filling actions for:
NameBirth Date(format:YYYY-MM-DD, e.g.,2024-05-15)Type(select dropdown; valid options includecat,dog,lizard,snake,bird,hamster)- Submit button (
Add Pet)
- Represents the form at
- Implement
OwnerRegistrationAndPetE2ETestsundersrc/test/java/org/springframework/samples/petclinic/e2e/:- Test name:
testRegisterNewOwnerAndAddNewPet - Scenario flow:
- Navigate to
/owners/findand click "Add Owner". - Fill the owner registration form with unique test data (e.g., first name:
Kak, last name:Burhan, address:Jl. Buntu 12, city:Ciburhan, telephone:7501234567) and submit. - Assert that the browser redirects to
/owners/{id}displaying theOwner Informationheading with the submitted owner information. - Click "Add New Pet".
- Fill the pet creation form (e.g., name:
Garong, birthdate:2024-01-01, type:cat) and submit. - Assert that the browser redirects back to the
Owner Informationpage. - Assert that the newly created pet is visible in the "Pets and Visits" table with the correct pet type and birthdate.
- Navigate back to
/owners/find, search by the new owner's last name (Burhan), and verify that the owner and pet record are successfully loaded from the database.
- Navigate to
- Test name:
Run your new E2E test and verify it passes:
1 | |
Deliverables
At the end of this exercise, commit and push your changes to your fork on GitLab CSUI under the task/3-mutation-and-e2e branch:
- A Markdown file named
EXERCISE_3_REPORT.mdlocated in the root of your repository (see template below). - Updated fork of Spring Petclinic with your changes, including the new test cases.
- Include at least one trace sample (e.g., a
trace_1.zipfile) that can be viewed in Playwright Trace Viewer.
The due date for this exercise is: Tuesday, 8 November 2026, 23:55 UTC+7.
Submit the URL of your forked repository and branch to the designated submission slot on SCELE before the deadline.
GenAI Usage Policy
This exercise allows GenAI and LLM tools as learning materials and tools. Even so, it is still imperative for you as course participant of SQA and user of GenAI to factually check the responses generated by GenAI.
The use of GenAI does not mean you can entirely delegate your learning process to GenAI. You enrolled in a course to learn and obtain knowledge and skills. Do not make GenAI the one that does the learning, turning you into a "meat proxy" for it.
Allowed Uses
- Setting up CI/CD pipeline on GitLab CSUI.
- Generating initial boilerplate skeletons for Page Object classes based on HTML structures.
- Clarifying Playwright locator APIs and ARIA accessibility roles.
- Explaining trace analysis and debugging failed assertions.
Prohibited Uses
- Blindly pasting AI-generated tests without running, understanding, and validating them locally.
- Generating test execution logs or Trace Viewer screenshots in your report.
Report Template
Use the following Markdown template for EXERCISE_3_REPORT.md:
Note: you can write your report in English or Bahasa Indonesia.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
GenAI Use Disclosure
Antigravity CLI with Gemini 4 Hydrogen model was used to:
- Proofread this document.
- Draft the exercise instructions about POM pattern.
- Generate the POM pattern code examples based on Spring Petclinic codebase.
We claim no authorship of the POM pattern code examples except the abstract test suite, which based on a prior work made by the teaching team. However, we have verified the generated code, and we have prior experience in implementing POM pattern. Hence, we release the code under CC0 1.0 Universal (public domain). We have reviewed and edited the generated text.
References
- PIT Mutation Testing Documentation
- Pitest Maven Quickstart Guide
- Paul Ammann & Jeff Offutt, Introduction to Software Testing, 2nd Edition (Cambridge University Press), Chapter 8: Syntax-Based Testing (Mutation Testing).
- Microsoft Playwright for Java Documentation
- Playwright Java: Page Object Models
- Playwright Java: Locators & ARIA Roles
- Playwright Java: Trace Viewer
- Spring Boot Testing: Random Port