Karate est un framework open-source basé sur Java, conçu pour les tests d'API, le mock d'API, et plus encore. Il utilise une syntaxe inspirée de Gherkin (comme Cucumber) pour écrire des tests clairs et lisibles.
Ajoutez Karate comme dépendance dans votre projet Maven :
<dependency>
<groupId>com.intuit.karate</groupId>
<artifactId>karate-apache</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
Si vous utilisez Gradle :
testImplementation 'com.intuit.karate:karate-apache:1.3.0'
Organisez votre projet comme suit :
src/
test/
java/
examples/
api/
sample.feature
karate-config.js
Créez un fichier nommé karate-config.js pour définir les variables globales :
function() {
return {
baseUrl: 'https://jsonplaceholder.typicode.com'
};
}
Écrivez un test dans sample.feature :
Feature: API Testing with Karate
Scenario: Get a post by ID
Given url baseUrl + '/posts/1'
When method GET
Then status 200
And match response contains { id: 1, userId: 1 }
Exécutez le test avec Maven :
mvn test -Dtest=examples.api.sample
Scenario: Create a new post
Given url baseUrl + '/posts'
And request { title: 'New Post', body: 'This is a new post.', userId: 1 }
When method POST
Then status 201
And match response contains { id: '#notnull' }
Créez un mock server avec Karate :
Feature: Mock API
Scenario: Mock a GET request
Given path '/hello'
And method GET
Then status 200
And response { message: 'Hello, Karate!' }
Karate prend en charge les tests de performance via karate-gatling.
dependencies {
implementation 'com.intuit.karate:karate-gatling:1.3.0'
}
Le Page Object Model peut être simulé avec des fichiers réutilisables.
// user-api.feature
Feature: User API
Scenario: Get a user by ID
Given path '/users/' + userId
When method GET
Then status 200
Feature: Main Test
Background:
* def UserAPI = call read('classpath:examples/api/user-api.feature')
* def userId = 1
Scenario: Test user API
* call UserAPI