How to write your first load test script using Gatling

What is Gatling?

Gatling is a powerful load testing tool that uses Akka actors for simulating a huge load. The tests are written in Scala. Gatling uses DSL, which makes it easy to understand and write tests with very minimal knowledge of Scala.

Gatling comes in both open source and enterprise versions. In this shot, we will use the open-source version of Gatling to show it’s capabilities and usage.

Akka actors: “The actor model provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct, concurrent, and parallel systems.” - Akka Documentationhttps://doc.akka.io/libraries/akka/current/typed/actors.html

Example - Gatling load test simulation

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class SampleSimulation extends Simulation {
val httpProtocol = http
.baseUrl("https://reqres.in/api/users")
.acceptHeader("*/*")
.doNotTrackHeader("1")
.userAgentHeader(
"Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"
)
.disableWarmUp
.disableCaching
val getScenario = scenario("BasicSimulation - GET")
.exec(
http("GET request")
.get("/")
.check(status.is(200))
)
setUp(
getScenario.inject(rampUsers(2) during (2 seconds))
).protocols(httpProtocol)
}

Code Explanation:

  • Step 1: Every simulation class has to extend Gatling’s Simulation class.

     class SampleSimulation extends Simulation
    
  • Step 2: Creating an HTTP configuration that can be re-used for all scenarios within the class; here we set the baseURL, any common request headers, etc.

     val httpProtocol = http
      .baseUrl("https://reqres.in/api/users")
      .acceptHeader("*/*")
      .doNotTrackHeader("1")
      .userAgentHeader(
        "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"
      )
      .disableWarmUp
      .disableCaching
    
    
  • Step 3: Creating a scenario for which we are going to generate a load. In this case, we are executing a GET call for the given target URL (baseURL is already specified in the above step) and assert the response status code as 200.

    val getScenario = scenario("BasicSimulation - GET")
      .exec(
        http("GET request")
          .get("/")
          .check(status.is(200))
      )
    
    
  • Step 4: In this step, we generate the specified load for the given scenario by injecting a load of two users for a duration of two seconds, and by setting the protocol configuration as httpProtocol.

    setUp(
      getScenario.inject(rampUsers(2) during (2 seconds))
    ).protocols(httpProtocol)
    
    

That’s it! You have written your first load test using Gatling.

Free Resources