TestFly Guide
This page is a learning path. Read it top to bottom and you know how TestFly fits together, what to use when, and which detail page to open next. It does not repeat the reference pages. Each section gives the mental model, one short example, the mistakes people make most, and links.
Examples use TestFly 1.1.0, the current release on Maven Central.
1. What TestFly is
TestFly is a Java 21 SDK for test automation in several domains with one configuration file, one lifecycle and one report:
| Domain | Status | Notes |
|---|---|---|
| Web UI | stable | Selenium WebDriver through a driver provider SPI; the raw WebDriver stays available |
| REST API | stable | Built-in ApiClient, JSONPath, schema checks, mocking |
| Load | stable | jdk engine built in, gatling engine optional |
| Native mobile | incubating | Android and iOS through a mobilecli server you install; the API may change in a minor release |
| AI | optional | Needs a provider key; each feature is opt-in |
Selenium is one adapter, not the architecture. Locators, waits, steps, retry, reports and CI integration do not depend on the driver, and the other domains do not start a browser.
testfly.yml
|
v
bootstrap: SuiteExecutionListener (TestNG), CucumberHooks, TestFlyExtension (JUnit 5)
| loads and validates config, registers report adapters
v
base class: BaseTest | BaseApiTest | BaseLoadTest | BaseMobileTest | BaseJUnit5Test | ...
| per test: thread-confined driver, step log, retry, quarantine
+--> Locator + WaitEngine (web: auto-waiting actions, web-first assertions)
+--> ApiClient (REST: requests, auth, mocks, schema checks)
+--> load engine (jdk | gatling: scenarios, SLAs, baselines)
+--> MobileScreen (native: page objects, auto-waiting locators)
|
v
reports: HTML, JUnit XML, Allure, ReportPortal, CI quality gates
Common mistakes
- Treating TestFly as a Selenium wrapper only. API, load and mobile tests use the same config and report.
- Creating or quitting a
WebDriveryourself. The framework owns the driver lifecycle. - Expecting every feature on by default. Healing, recording, tracing and AI analysis are off until you enable them.
Detail pages: Introduction, Why TestFly, BaseTest
2. Choose your stack
Pick a domain and a test engine, then use the matching base class. The optional dependencies are declared <optional> in the TestFly POM, so your project must add them. Versions below are the ones TestFly 1.1.0 is built against.
| Domain | TestNG | JUnit 5 | Cucumber |
|---|---|---|---|
| Web UI | BaseTest | BaseJUnit5Test, or @EnableTestFly, or @ExtendWith(TestFlyExtension.class) | runner extends BaseCucumberTest, steps extend BaseCucumberSteps |
| REST API | BaseApiTest | BaseJUnit5ApiTest | steps extend BaseCucumberSteps; tag scenarios @api (no browser) |
| Load | BaseLoadTest and @LoadTest | no dedicated base class | not documented |
| Native mobile (incubating) | BaseMobileTest or @MobileTest | BaseJUnit5MobileTest or @MobileTest | tag @mobile; steps implement MobileSupport |
TestNG 7.9.0 and Selenium 4.51.0 are regular dependencies of TestFly. Everything else is opt-in:
| You use | Add to your build | Version |
|---|---|---|
| JUnit 5 | org.junit.jupiter:junit-jupiter-api (or junit-jupiter), org.junit.platform:junit-platform-launcher | 5.10.2, 1.10.2 |
| Cucumber | io.cucumber:cucumber-java, io.cucumber:cucumber-testng | 7.20.1 |
assertSchema(...) | com.networknt:json-schema-validator | 1.4.3 |
assertOpenApi(...) | com.atlassian.oai:swagger-request-validator-core | 2.39.0 |
mockServer() (WireMock) | org.wiremock:wiremock-standalone | 3.5.4 |
| Gatling load engine | io.gatling.highcharts:gatling-charts-highcharts (see engines) | 3.16.0 |
excel: test data | org.apache.poi:poi-ooxml | 5.4.0 |
| IMAP e-mail provider | com.sun.mail:jakarta.mail | 2.0.2 |
| ReportPortal | com.epam.reportportal:agent-java-testng / agent-java-cucumber7 / agent-java-junit5 | 5.6.8 / 5.4.10 / 5.5.8 |
Native mobile needs no Maven dependency, but it needs the external mobilecli tool (section 9).
Common mistakes
- Calling an optional feature without its dependency.
assertOpenApithrowsIllegalStateExceptionwith the missing snippet in the message. - Expecting
BaseTestorBaseApiTestto offerload(). OnlyBaseLoadTestdoes. - Mixing engines in one class. A class belongs to one engine.
Detail pages: JUnit 5, Cucumber, Gradle, Execution engines
3. Project setup
Add the dependency:
<dependency>
<groupId>io.github.hakanngul</groupId>
<artifactId>testfly</artifactId>
<version>1.1.0</version>
</dependency>
Create testfly.yml in the project root or in src/test/resources:
execution:
mode: local # local | remote | browserstack | saucelabs
baseUrl: https://your-app.example.com
browser:
name: chrome
headless: false
timeouts:
explicit: 10 # seconds, WaitEngine and Locator waits
pageLoad: 30
retry:
enabled: true
maxAttempts: 1 # retries after the first failure
TestFly refuses to start when execution.mode is missing or not one of the four values. The loader also requires browser.name (or browser.matrix), execution.baseUrl, and positive timeouts.explicit and timeouts.pageLoad. A profile for native mobile only needs a mobile: block.
How configuration is found and resolved
- File location, first match wins:
-Dtestfly.config=/path/file.yml, then the classpath, then the working directory. -Dtestfly.profile=ciselectstestfly-ci.ymlinstead oftestfly.yml. A profile is a complete file; it is not merged withtestfly.yml.- Inside string values,
${VAR}and${VAR:-default}are resolved from, in this order: the.envfile next topom.xml, the shell environment, Java system properties, then the default. - The optional
features:block switches whole modules on or off above their own settings. - A few runtime switches are system properties, for example
testfly.shard.total,testfly.shard.index,testfly.reports.dir,testfly.merge. - When a CI system is detected, TestFly forces
browser.headless: trueand tunesthreadCountif you left it at 1.
Secrets belong in the environment, referenced as placeholders:
api:
auth:
admin:
type: bearer
token: ${ADMIN_TOKEN}
Common mistakes
- Putting
${VAR}in a boolean or number (headless: ${HEADLESS:-true}). Placeholders only work in strings; use a profile file instead. - Expecting a profile to override only some keys. It replaces the whole file.
- A
.envvalue silently beating a shell variable. The.envfile wins on purpose, so a stale exported credential cannot override the checked-out project. - Committing real keys. Use
${ENV_VAR}and keep.envout of version control.
Detail pages: Getting Started, Configuration Reference, testfly.yml guide
4. Your first web test
Keep selectors and screen behaviour in a page object that extends BasePage. Prefer semantic locators, which target what the user sees (role, label, test id), and fall back to CSS only when no semantic handle exists.
import io.testfly.locator.Role;
import io.testfly.test.BasePage;
public class LoginPage extends BasePage {
public LoginPage() {
super();
}
public void openPage() {
open("/login");
}
public void signIn(String user, String password) {
getByLabel("Username").fill(user);
getByLabel("Password").fill(password);
getByRole(Role.BUTTON, "Sign in").click();
}
public void shouldShowDashboard() {
assertThat(getByRole(Role.HEADING, "Dashboard")).isVisible();
}
}
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test(description = "Valid user sees the dashboard")
public void validLogin() {
LoginPage login = new LoginPage();
login.openPage();
login.signIn("admin", System.getenv("APP_PASSWORD"));
login.shouldShowDashboard();
softAssert(getByTestId("welcome")).containsText("admin");
softAssert().that(getTitle().contains("Dashboard"), "Title names the dashboard");
}
}
What to know:
- Locator order.
getByRole,getByLabel,getByPlaceholder,getByText,getByTestIdfirst; thenfind("css")orfind(By). The test-id attribute defaults todata-testid(locators.testIdAttribute).Locatoris chainable:filter,withText,within,nth,first,last. - Actions auto-wait.
click,fill/type,hoverand friends wait until the element is visible, enabled, stable and not covered, then act. A failure names the element and the reason. - Assertions retry.
assertThat(locator).isVisible()polls until it holds ortimeouts.explicitruns out. Use.within(Duration)to override per assertion. - Soft assertions (
softAssert(...)) collect failures and fail the test at the end, so one run shows every problem. - No
Thread.sleep. A fixed sleep is either too short (flaky) or too long (slow). Waiting on a condition through a locator, an assertion orWaitEngine.waitForVisible(By)is both faster and stable. - Raw Selenium is still there.
getDriver()returns the current thread'sWebDriverwhen you need it.
Common mistakes
- Calling
new ChromeDriver()ordriver.quit()in a test. - Starting with CSS chains such as
div.modal > form button.btn-primarywhere a role and name would do. - Defining
open()with a different return type in a page object.open()already exists onBasePage. - Wrapping every step in explicit waits. Locator actions already wait.
Detail pages: BasePage, Accessibility-first locators, Smart locators, WaitEngine, Assertions, Why no Thread.sleep
5. Structuring a suite
Lifecycle. With TestNG, extending BaseTest registers the listeners. SuiteExecutionListener bootstraps the framework and writes the reports at the end. TestExecutionListener creates the driver just before each @Test method and quits it after. A failed test gets a screenshot automatically.
- TestNG: the driver does not exist in
@BeforeMethodor@AfterMethod. Put browser setup in the test or in@PreCondition. - JUnit 5:
TestFlyExtensioncreates the driver in itsbeforeEachcallback, so it exists in your own@BeforeEach. browser.lifecycle: per-test(default) gives a fresh browser per test.per-suitereuses one browser per thread (per test class in JUnit 5).
@PreCondition runs a named provider once per thread and restores its cookies and local storage for later tests. Typical use is logging in once:
public class AppConditions extends BaseConditions {
@ConditionProvider("loginAsAdmin")
public void loginAsAdmin() {
open("/login");
getByLabel("Username").fill("admin");
getByLabel("Password").fill(System.getenv("APP_PASSWORD"));
getByRole(Role.BUTTON, "Sign in").click();
}
}
Register the class in src/test/resources/META-INF/services/io.testfly.precondition.BaseConditions (one line, the class name), then use it:
@Test
@PreCondition("loginAsAdmin")
public void viewDashboard() {
open("/dashboard");
}
Test data. @TestData("csv:testdata/logins.csv") loads a row into getTestData(). JSON/YAML files, excel: and db: sources also exist.
Retry. Set retry.enabled and retry.maxAttempts, or annotate a method with @Retryable. maxAttempts counts retries after the first failure, so 1 means up to two runs. Without a retry: block nothing is retried, and retry.enabled: false disables @Retryable as well. In JUnit 5 only the test method body is re-run, not your @BeforeEach.
Parallel execution. Set execution.parallel (methods, classes, tests, instances), threadCount and maxActiveSessions. The driver lives in a ThreadLocal, so getDriver() always returns the calling thread's browser. Run TestNG through a suite file with matching parallel and thread-count. JUnit 5 uses junit-platform.properties. Keep test state out of static fields, and out of instance fields too when methods run in parallel; use local variables or ctx().
@NoBrowser marks a class or method that needs no WebDriver (database, API or file checks) but still extends BaseTest. Reports, retry and gates still apply.
Common mistakes
open()in@BeforeMethodwith TestNG. The driver is not there yet.- Sharing a page object or driver across threads through a static field.
- Setting
threadCountabovemaxActiveSessions. Extra threads wait up toexecution.sessionWaitSeconds(default 300) for a free slot. - Registering a
@ConditionProviderclass without the SPI file orPreConditionRegistry.register(...).
Detail pages: BaseTest, Browser lifecycle, @PreCondition, Retry, Parallel execution, External test data
6. API testing
Mental model. BaseApiTest (TestNG) and BaseJUnit5ApiTest (JUnit 5) give you the full lifecycle without a browser. ApiClient is a fluent builder: pick a method and path, add headers, auth and a body, call send(), then chain assertions on the ApiResponse. Relative paths resolve against api.baseUrl.
public class UserApiTest extends BaseApiTest {
@Test
public void createsAndReadsUser() {
ApiResponse created = apiPost("/users")
.body(Map.of("name", "Ada"))
.send()
.assertStatus(201);
ctx().set("userId", created.json("$.id"));
apiGet("/users/" + ctx().get("userId"))
.send()
.assertStatus(200)
.assertJson("$.name", "Ada");
}
}
- Auth.
ApiAuthfactories cover bearer, basic, API key (header or query), OAuth2 (client credentials, password, refresh), HMAC and digest. Set one per test withApiClient.setGlobalAuth(...), or name strategies underapi.authintestfly.ymland apply them with@UseAuth("name"). Global auth is thread-local and cleared after each test. - Schema checks.
assertSchema("schemas/user.json")validates against a JSON Schema and needsjson-schema-validator.assertOpenApi(specPath)validates the response against an OpenAPI 3 spec and needsswagger-request-validator-core. - Mocking.
ApiMockRulereturns synthetic responses without network access.mockServer()starts a WireMock server on a dynamic port; it needswiremock-standaloneand is a JVM singleton, so remove only your own stubs in parallel runs. @DependsOnApi("https://host/health")probes a URL once per suite and skips (does not fail) the test when it is down.- Hybrid tests.
BaseTestalso hasapiClient(): create data through the API, then verify it in the browser.
@Test
public void orderShowsAsPending() {
String id = apiPost("/api/orders").body(Map.of("productId", 42)).send()
.assertStatus(201).json("$.orderId");
open("/orders/" + id);
assertThat(getByTestId("status")).hasText("Pending");
}
Common mistakes
- Using
apiClient()andApiClient.get(...)inconsistently without a base URL. Setapi.baseUrlor pass absolute URLs. - Relying on static mock rules or global auth across parallel tests. They are per thread.
- Forgetting that
ApiResponse.json(path)returns a string; use the typed overloads when you need another type. - Enabling
api.logBodyon responses that hold secrets (see section 13).
Detail pages: API testing, Requests, Responses, Authentication, Schema validation, Mocking, Hybrid tests, Scenario and suite context
7. Cucumber
Mental model. A runner extends BaseCucumberTest, step classes extend BaseCucumberSteps (the same locators, assertions, apiClient() and ctx() as BaseTest), and CucumberHooks manages the driver per scenario.
@CucumberOptions(
features = "src/test/resources/features",
glue = {"com.example.steps", "io.testfly.cucumber"},
plugin = {"pretty", "io.testfly.cucumber.CucumberStepLogger"}
)
public class CucumberRunner extends BaseCucumberTest {
@Override
@DataProvider(parallel = true) // required for parallel scenarios
public Object[][] scenarios() {
return super.scenarios();
}
}
public class LoginSteps extends BaseCucumberSteps {
@When("they sign in as {string}")
public void signIn(String user) {
getByLabel("Username").fill(user);
getByRole(Role.BUTTON, "Sign in").click();
ctx().set("user", user);
}
}
- Glue.
io.testfly.cucumbermust be inglue, or no hooks run.CucumberStepLoggerputs Gherkin steps into the report timeline. - Tags.
@api,@nobrowserand@mobilestart no browser.@retryableor@retryable=Nsets retries for one scenario.@quarantine(name configurable withquarantine.cucumberTag) skips a scenario. ScenarioContext.ctx()is a thread-local store shared by all step classes of the running scenario. It is cleared after each scenario, so no dependency-injection container is needed.- IDE runs. Add
src/test/resources/cucumber.propertieswith the same glue and plugin, because IDE runners ignore@CucumberOptions.
Common mistakes
- Leaving out
io.testfly.cucumberinglue. - Setting
execution.paralleland expecting parallel scenarios. Cucumber-TestNG also needs@DataProvider(parallel = true). - Keeping state in step-class fields instead of
ctx()when several step classes need it. - Declaring
cucumber-javawithoutcucumber-testng, or with different versions.
Detail pages: BDD / Cucumber, Scenario and suite context, Quarantine
8. Load testing
Mental model. BaseLoadTest (TestNG) starts no browser. You describe a scenario, TestFly runs it on an engine, and you assert on the metrics. The jdk engine uses the JDK HttpClient with virtual threads and needs no extra dependency. The gatling engine runs in a forked JVM, supports workload models and simulations, and needs Gatling on your classpath. loadtest.engine: auto picks Gatling when present, otherwise the JDK engine.
@LoadTest(users = 25, rampUp = "5s", hold = "15s", engine = "jdk")
public class CatalogLoadTest extends BaseLoadTest {
@Test
public void catalog() {
load("/products").run()
.assertP95Below(300)
.assertErrorRateBelow(0.01);
}
@Test
public void searchOverride() {
load("/products?q=phone").users(40).run().assertP95Below(350);
}
}
- Settings resolve in this order: fluent scenario, method
@LoadTest, class@LoadTest, theloadtest:block intestfly.yml, then defaults.usersis clamped toloadtest.maxUsers. - Multi-step flows use
loadScenario(name).step(...). Several scenarios at once useloadSimulation(name)and need Gatling. - SLAs.
sla().p95Below(300).errorRateBelow(0.01)declares rules TestFly checks when the run ends, on both engines. - Baselines.
LoadBaseline.of(metrics).save(path)stores a run;result.assertNoRegression(baseline, Tolerance.percent(15))fails later runs that regress. - Target URL. Set
loadtest.baseUrlexplicitly.
Common mistakes
- Starting load from a class that extends
BaseTest. It has noload(). - Choosing
engine("jdk")and then using a workload model or simulation. Both are rejected before any request. - Treating
usersas a concurrency target. Users start evenly overrampUp. - Using thresholds copied from examples. Derive them from your SLOs and a measured baseline.
Detail pages: Getting started, Configuration, Fluent API, Annotations, Engines, Simulations and SLAs, Baselines, Reporting
9. Native mobile (incubating)
Everything in io.testfly.mobile is incubating: it is not annotated @TestFlyApi and may change in a minor release. CI runs the examples on Android emulators and an iOS simulator; real phones are not covered by CI.
What it needs. A mobilecli server (1.0.20 or newer) that you install yourself; TestFly does not bundle it. Android needs the Android SDK. iOS simulators need Xcode on macOS, plus mobilecli's agent installed once on the device. A mobile: block in the active testfly.yml turns the module on:
mobile:
platform: ios # android | ios
deviceId: ${MOBILE_DEVICE_ID:-} # empty: the only online device of the platform
app:
bundleId: com.example.app
Page objects. A MobilePage holds the iOS and Android selector of an element side by side. Creating the page waits for its @WaitFor fields.
public class HomePage extends MobilePage {
@MobileFind(ios = "HomeScreen.loginButton", android = "com.example:id/btnHome")
@WaitFor
private MobileLocator loginButton;
public LoginPage openLogin() {
loginButton.tap();
return new LoginPage();
}
}
public class LoginTest extends BaseMobileTest {
@Test
public void opensLogin() {
new HomePage().openLogin();
}
}
Limits. One device per test and one test per device at a time. App state cannot be cached like browser cookies, so a mobile @PreCondition runs before every test unless mobile.app.reset: none. Cucumber does not read @PreCondition; use a Background. WebViews must be debuggable or inspectable. Credentials in examples come from environment variables only.
Common mistakes
- Giving a
@MobileFindfield an initial value such as= null. It overwrites the locator. - Looking up an Android emulator by adb serial. The id is the AVD name.
- Expecting a browser: mobile tests skip it.
- Assuming real-device coverage. Only emulators and a simulator are exercised in CI.
Detail pages: Mobile getting started, Locators, Page objects, Configuration, CI, Troubleshooting
10. Reliability and debugging
| Tool | Default | How to use it |
|---|---|---|
| Screenshot on failure | on | Embedded in the HTML report as Base64; step("name", true) adds step screenshots |
| Step logging | on | step("name") builds the timeline in the report |
| Console errors | off | browser.captureConsoleErrors: true; browser.failOnConsoleErrors: true fails the test |
| Video | off | recording.enabled: true, mode retain-on-failure by default |
| Tracing | off | tracing.enabled: true writes a standalone HTML bundle with step timeline and snapshots |
| Self-healing | off | locators.selfHealing: true |
| Quarantine | on | List tests in testfly-quarantine.yml; they are skipped before a browser starts |
| Flakiness history | on (features.flakiness) | Scores flaky tests from run history, shown in the report |
Self-healing as implemented today. When a plain find("css") or find(By) locator times out, TestFly tries fallback locators derived from the original (id, name, text, last class, data-testid, placeholder), then a local fuzzy match. A heal is logged: the report shows a "healed" badge and target/healed-locators.json lists the old and new locator. Semantic getBy* locators and chained locators (filter, nth, within, and so on) are not healed. If nothing matches, the original exception is thrown. AI healing is a separate, optional step: locators.aiHealing: true asks your configured AI provider after the static strategies fail. Treat every heal as a to-do to fix the selector.
Quarantine keeps a known-flaky test from blocking the build without deleting it:
quarantine:
- com.example.tests.LoginTest#loginWithExpiredSession
- test: com.example.tests.SearchTest#searchWithSpecialChars
reason: "Unicode handling broken, tracked in the issue tracker"
Common mistakes
- Leaving self-healing on and never reading
healed-locators.json. Rot hides. - Using retry to hide a real bug. A passing retry still shows as retried.
- Turning on recording and tracing everywhere. Use
retain-on-failureand enable tracing where you debug. - Letting a
features:block override a module you enabled in its own section; an explicitfalsethere wins.
Detail pages: Self-healing, Console errors, Screenshots, Video recording, Tracing, Step logging, Quarantine
11. Reports and CI
Reports. After a run TestFly writes target/testfly-report.html (a tabbed HTML dashboard) and target/testfly-metrics.json. testfly.reports.dir changes the folder. JUnit XML goes to target/surefire-reports/TEST-TestFly.xml, which CI servers parse natively. Allure results (reporting.allure.enabled: true) go to target/allure-results/; rendering them needs the Allure CLI. ReportPortal is enabled with reporting.reportportal.enabled: true and its agent dependency.
CI. TestFly detects the CI provider and records branch, commit and build URL as metadata. Quality gates fail the build from testfly.yml:
browser:
name: chrome
headless: true
execution:
mode: local
baseUrl: https://staging.example.com
parallel: methods
threadCount: 4
maxActiveSessions: 4
timeouts:
explicit: 10
pageLoad: 30
ci:
failOnPassRateBelow: 90 # percent; 0 disables
maxFlakyTests: 3 # retried tests; -1 disables
Run it with mvn test -Dtestfly.profile=ci. To spread a suite over several CI workers, pass -Dtestfly.shard.total=4 -Dtestfly.shard.index=0 (one index per worker), or set CI_NODE_TOTAL and CI_NODE_INDEX. The built-in interceptor then runs only that worker's share of the test methods.
Common mistakes
- Looking for the HTML report in the wrong folder. It follows
testfly.reports.dir, ortarget/(andbuild/for a Gradle-only project). - Using a profile file that omits required keys. Every profile must be complete.
- Sharding without distinct indexes per worker.
- Expecting Allure HTML without the Allure CLI.
Detail pages: HTML report, JUnit XML, Allure, ReportPortal, Quality gates, CI metadata, Smart test sharder, GitHub Actions, Jenkins, Bitbucket Pipelines
12. AI features
AI is optional. Nothing calls a model unless a feature that uses one is switched on and a provider key is configured. The ai: block selects the provider (claude by default; gemini and openai-compatible also work) and takes the key as a placeholder:
ai:
provider: claude
apiKey: ${AI_API_KEY}
failureAnalysis: true # off by default; explains failures in the report
What exists in the Java runtime:
- Failure analysis (
ai.failureAnalysis) and patch generation (ai.generatePatch), both off by default. - AI healing (
locators.aiHealing), off by default, after static healing fails. act("goal"),byIntent("...")andassertWithAi(...), which run only when your test calls them.
ai.enabled (default true) and features.ai are the master switches: set either to false and no AI surface runs. Review model-generated output before you rely on it. The separate @testfly/mcp Node package and the IDE tooling are different from the Java runtime; start at the AI overview.
Common mistakes
- Committing
ai.apiKey. Use${AI_API_KEY}. - Assuming AI features work offline or in a network-restricted CI.
- Mixing up the Java runtime AI settings with your IDE assistant's configuration.
Detail pages: AI overview, Agentic testing, MCP bridge and CLI
13. Security and secrets
- Keys stay out of files. Reference
${ENV_VAR}intestfly.yml; keep.envuntracked. - URLs are masked in the
[API]step log, cURL lines, exception messages and the report: userinfo becomes***, and values of sensitive query parameters (api_key,token,access_token,password, and more) become***. Add names withapi.maskedQueryParams.ApiResponse.requestUrl()still returns the real URL, so do not log it. - Headers are masked.
api.maskedHeadersdefaults toAuthorization,CookieandX-Api-Key; header names that look like credentials (token,secret,auth,session, and so on) are masked too. - Bodies are masked in assertion-failure messages and
ApiExceptionmessages, which show a masked body capped at 300 characters. Withapi.logBody: true, bodies are attached to the step log truncated but not masked, so leave it off when responses carry secrets. - Path segments are not masked. Do not put secrets in paths.
api:
maskedQueryParams: [x-tenant-secret, otp]
logBody: false
Common mistakes
- Logging
ApiResponse.requestUrl()yourself. - Turning on
logBodyorlogCurlin a shared CI with production credentials. - Hard-coding passwords in page objects. Read them from the environment.
Detail pages: API authentication, API logging and reporting, Configuration Reference
14. Best-practice checklist and pitfalls
Checklist
- One
testfly.ymlwith all required keys; profiles are complete files. - Secrets only as
${ENV_VAR}. - Semantic locators first; page objects own selectors.
- No
Thread.sleep, no manual driver code. - Optional dependencies declared for every feature you use.
- Tests independent and parallel-safe: no static mutable state, per-thread auth and mocks.
- Retry and healing reviewed, not trusted blindly; flaky tests quarantined with a reason.
- Quality gates and sharding set in CI.
Pitfalls
| Symptom | Cause and fix |
|---|---|
Startup fails with Execution mode must be specified or another config error | A required key is missing: execution.mode, execution.baseUrl, browser.name, timeouts.explicit, timeouts.pageLoad. Add it. |
IllegalStateException mentioning a dependency snippet | An optional dependency (OpenAPI validator, WireMock, Gatling, Cucumber, ReportPortal) is not in your build. Add it. |
| Selenium reports a driver and browser version mismatch | An old chromedriver on PATH can be used instead of the one Selenium Manager would download. Remove it or update it. |
| Chrome does not start in Docker or Kubernetes | TestFly adds --no-sandbox, --disable-dev-shm-usage and --disable-gpu when it detects a container. If your runtime is not detected, add them under browser.arguments. |
WebDriver not initialized for current thread | Browser code in a TestNG @BeforeMethod or @AfterMethod. Move it to the test or @PreCondition. |
| Parallel runs collide | Fixed ports, shared accounts or shared files. Use dynamic ports (mockServer() does), per-thread data and unique file names. |
| Cucumber runs scenarios one by one | Missing @DataProvider(parallel = true) on scenarios(). |
| Boolean config value fails to parse | A ${VAR} placeholder in a non-string field. Use a profile file. |
Detail pages: Configuration Reference, Browser support, Parallel execution
15. Where to go next
| I want to... | Go to |
|---|---|
| Install and run a first test | Getting Started |
| Look up a config key | Configuration Reference |
| Write page objects | BasePage |
| Find stable locators | Accessibility-first locators |
| Understand waiting and actionability | WaitEngine |
| Assert on UI state | Assertions |
| Log in once for many tests | @PreCondition |
| Run tests in parallel | Parallel execution |
| Use JUnit 5 or Gradle | JUnit 5, Gradle |
| Write BDD scenarios | BDD / Cucumber |
| Test a REST API | API testing |
| Validate against OpenAPI | Schema validation |
| Drive tests from CSV, Excel or a database | External test data |
| Check e-mail or OTP | E-mail verification |
| Control time in a test | Clock mocking |
| Run a load test | Load testing |
| Test a native app | Native mobile |
| Run on BrowserStack, Sauce Labs or a Grid | Cloud execution |
| Fix flaky tests | Retry, Self-healing, Quarantine |
| Debug a failure | Tracing, Video recording, Console errors |
| Publish reports | HTML report, Allure, ReportPortal |
| Set up CI | GitHub Actions, Jenkins, Quality gates |
| Extend TestFly | Plugins, Hooks, Custom drivers |
| Use AI features | AI overview |
| Migrate from another tool | From Selenium + TestNG |
| See runnable example projects | Working example projects |