# TestFly Part 9: In-process load testing in Java with Gatling and K6

URL: https://hakangul.lovable.app/blog/testfly-part-9-k6-gatling-load-testing-in-java
Author: Hakan Gül — Team Lead Senior Test Automation Engineer
Published: 2026-09-10
Updated: 2026-10-18
Category: test-automation
Tags: TestFly, Load Testing, Gatling, K6, Performance Testing, Java, SDET

> TestFly 1.1.0 runs Gatling/K6 load tests from the same Java test class as your UI and API tests, and checks P95 SLOs with assertions.

## English

TestFly 1.1.0 adds built-in load and performance testing, powered by Gatling and lightweight virtual threads. You can write, parameterize and run high-concurrency load scenarios inside ordinary TestNG or JUnit 5 test classes, without switching to an external tool.

## Why keep functional and load tests together

Performance testing often comes last in the development cycle, or it lives in a separate toolchain such as the JMeter GUI or standalone scripts. That split causes a few problems:

- Test data and authentication setup get duplicated between the functional and performance repos.
- Performance tests run rarely, often right before a production release.
- CI/CD quality gates are hard to configure when the tests run on different runners.

In TestFly you declare load simulations with the same test classes, base configuration (`testfly.yml`) and assertions you already use for WebUI and API automation.

## How load testing works in TestFly

There are two ways to write a load test.

### 1. Declarative mode with `@LoadTest`

Add `@LoadTest` to a test method to set the number of concurrent virtual users and the ramp-up phase:

```java
package io.testfly.examples.loadtest;

import io.testfly.loadtest.LoadTest;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class SimpleLoadTest extends BaseTest {

    @Test
    @LoadTest(users = 100, rampUpSeconds = 15, durationSeconds = 60)
    public void testCheckoutUnderSurgeTraffic() {
        apiClient().post("/api/checkout")
            .body("{\"cartId\": 1024}")
            .send()
            .assertStatus(200);
    }
}
```

### 2. Fluent programmatic DSL with `load()`

For multi-step user journeys and dynamic feeders, use the fluent `LoadScenario` DSL:

```java
package io.testfly.examples.loadtest;

import io.testfly.loadtest.LoadScenario;
import io.testfly.loadtest.LoadTestFeeder;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class AdvancedLoadJourneyTest extends BaseTest {

    @Test
    public void simulateUserBrowsingJourney() {
        LoadTestFeeder users = LoadTestFeeder.csv("testdata/users.csv");

        LoadScenario.scenario("Search and Add to Cart")
            .feed(users)
            .step("Browse Catalog", client -> client.get("/products?q=shoes").send().assertStatus(200))
            .pause(1000)
            .step("Add to Cart", client -> client.post("/cart/items").body("{\"id\": 42}").send().assertStatus(201))
            .users(500)
            .rampUp(20)
            .run();
    }
}
```

## Checking performance SLOs in code

Metrics only help if something checks them automatically. TestFly records the timing of every request with millisecond precision and computes the standard percentiles (P50, P90, P95, P99):

| Percentile Metric | Meaning | Typical SLO Target |
|:---|:---|:---|
| **P50 (Median)** | 50% of requests completed faster than this time | < 150 ms |
| **P90** | 90% of requests completed faster than this time | < 350 ms |
| **P95** | 95% of requests completed faster than this time | < 500 ms |
| **P99** | Tail latency affecting 1% of users | < 1200 ms |

Write your service-level objectives as assertions and the build fails on its own when performance regresses:

```java
import static io.testfly.loadtest.LoadTestAssert.*;

assertP95Below(Duration.ofMillis(450));
assertErrorRateBelow(0.01); // Less than 1% failures
```

## Reporting

TestFly produces an interactive HTML performance report with:

- live latency distribution curves and percentile breakdowns
- HTTP status code distributions (2xx, 4xx, 5xx)
- direct export to Allure Reports and ReportPortal, so load results show up in the same dashboards as the rest of your tests

## FAQ

### Does TestFly require JMeter or an external binary?

No. Simulations run in-process on Gatling's engine or on native Java virtual threads, so there is no external runtime binary to install.

### Can I run load tests in CI/CD without overwhelming local machines?

Yes. Load tests run headless in CI (GitHub Actions, Bitbucket, Jenkins). For very large loads (100k+ RPS) you can schedule containerized runner pods on Kubernetes.

### Can I use API authentication tokens in load tests?

Yes. TestFly's `ApiClient` passes Bearer tokens and session headers to the load test steps.

## Türkçe

TestFly 1.1.0 ile Gatling ve Java sanal iş parçacıkları (virtual threads) üzerine kurulu dahili yük ve performans testi desteği geldi. SDET'ler yüksek eşzamanlılıktaki yük senaryolarını harici bir araca geçmeden, doğrudan standart TestNG veya JUnit 5 test sınıflarında yazıp parametrelendirebilir ve doğrulayabilir.

## Fonksiyonel testler ve yük testleri neden aynı yerde durmalı

Performans testleri çoğu zaman sürecin sonuna bırakılır ya da JMeter gibi arayüzlü ayrı araçlarda yürütülür. Bu ayrımın bedeli şöyle:

- Fonksiyonel testlerdeki test verisi ve auth kurulumu yük testleri için baştan yazılır.
- Performans testleri seyrek koşulur, genelde canlıya çıkıştan hemen önce. Bu da Shift-Left yaklaşımıyla çelişir.
- Farklı araçların çıktılarını CI/CD hattında birleştirip kalite kapısı kurmak zorlaşır.

TestFly'da yük testlerini aynı `BaseTest` altyapısı, aynı `testfly.yml` ayarları ve aynı assertion kütüphanesiyle yazarsınız.

## TestFly ile yük testi nasıl yazılır

İki yazım şekli var.

### 1. `@LoadTest` ile deklaratif yazım

Test metodunu `@LoadTest` anotasyonuyla işaretleyip eşzamanlı sanal kullanıcı sayısını ve artış (ramp-up) süresini verirsiniz:

```java
package io.testfly.examples.loadtest;

import io.testfly.loadtest.LoadTest;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class BasitYukTesti extends BaseTest {

    @Test
    @LoadTest(users = 100, rampUpSeconds = 15, durationSeconds = 60)
    public void yukAltindaOdemeHizmetiTesti() {
        apiClient().post("/api/checkout")
            .body("{\"cartId\": 1024}")
            .send()
            .assertStatus(200);
    }
}
```

### 2. `LoadScenario` ile akıcı (fluent) DSL

Çok adımlı kullanıcı akışlarını ve dinamik veri besleyicilerini (feeder) bu DSL ile yazarsınız:

```java
package io.testfly.examples.loadtest;

import io.testfly.loadtest.LoadScenario;
import io.testfly.loadtest.LoadTestFeeder;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class GelismisGezintiTesti extends BaseTest {

    @Test
    public void kullaniciAlisverisGezintisi() {
        LoadTestFeeder kullanicilar = LoadTestFeeder.csv("testdata/users.csv");

        LoadScenario.scenario("Katalog Arama ve Sepete Ekleme")
            .feed(kullanicilar)
            .step("Katalog Arama", client -> client.get("/products?q=ayakkabi").send().assertStatus(200))
            .pause(1000)
            .step("Sepete Ekle", client -> client.post("/cart/items").body("{\"id\": 42}").send().assertStatus(201))
            .users(500)
            .rampUp(20)
            .run();
    }
}
```

## Performans kalite kapıları (SLO) nasıl denetlenir

Ölçülen süreler otomatik olarak P50, P90, P95 ve P99 yüzdeliklerine çevrilir:

| Yüzdelik (Percentile) | Anlamı | Tipik Hedef (SLO) |
|:---|:---|:---|
| **P50 (Medyan)** | İsteklerin %50'sinin tamamlanma süresi | < 150 ms |
| **P90** | İsteklerin %90'ının tamamlanma süresi | < 350 ms |
| **P95** | İsteklerin %95'inin tamamlanma süresi | < 500 ms |
| **P99** | En yavaş %1'lik kuyruk gecikmesi | < 1200 ms |

Hedeflerinizi kodda assertion olarak yazarsanız performans gerilediğinde (regression) CI derlemesi kendiliğinden kırılır:

```java
import static io.testfly.loadtest.LoadTestAssert.*;

assertP95Below(Duration.ofMillis(450));
assertErrorRateBelow(0.01); // %1'den az hata oranı
```

## SSS

### TestFly yük testi için JMeter ya da harici bir kurulum ister mi?

Hayır. TestFly, Gatling motorunu ve Java sanal iş parçacıklarını kendi içinde çalıştırır. Ayrıca bir binary kurmanız gerekmez.

### TestFly yük testleri CI/CD pipeline'ında koşulabilir mi?

Evet. GitHub Actions, Jenkins ve Bitbucket Pipelines üzerinde headless çalışır. Yüksek hacimli yükler için Docker ve Kubernetes podlarıyla yatayda ölçeklenebilir.

### API yetkilendirmesi (Bearer token) yük testlerine dahil edilebilir mi?

Evet. `ApiClient` üzerinden alınan token ya da oturum çerezleri senaryodaki tüm adımlara otomatik olarak aktarılır.
