<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maxime Pontoire on Medium]]></title>
        <description><![CDATA[Stories by Maxime Pontoire on Medium]]></description>
        <link>https://medium.com/@maxime.pontoire?source=rss-239b2b51e9d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0Wu6PWZkbaghNbIQaKXq0g.jpeg</url>
            <title>Stories by Maxime Pontoire on Medium</title>
            <link>https://medium.com/@maxime.pontoire?source=rss-239b2b51e9d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:24:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxime.pontoire/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tester automatiquement une application Flutter]]></title>
            <link>https://medium.com/sncf-connect-tech/tester-automatiquement-une-application-flutter-77e8aa471cb?source=rss-239b2b51e9d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e8aa471cb</guid>
            <category><![CDATA[gherkin]]></category>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Maxime Pontoire]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 15:27:38 GMT</pubDate>
            <atom:updated>2025-03-17T13:12:10.127Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@maxime.pontoire/automated-tests-of-a-flutter-application-3d878e9d8a61"><strong><em>This article is also available in English.</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTaqJMKllx6jVZ7b3uCAWg.png" /><figcaption>SNCF Connect developers are loving Flutter</figcaption></figure><h3>Introduction</h3><p>De plus en plus d’applications sont développées en utilisant le framework Flutter, afin d’être disponibles à la fois sur iOS et Android (avec une grosse partie du code mutualisé). Depuis 2 ans, la communauté a rendu ce framework stable et a fourni de nombreux outils pour tester le code et les applications générées. Durant la même période, nous avons commencé à construire SNCF Connect, une application aujourd’hui utilisée par des millions de Français. Notre ambition était d’aller vers le “delivery continu” grâce à des solutions à l’état de l’art et des tests automatisés.</p><p>Si vous avez déjà développé une application mobile, en utilisant les SDK natifs, vous savez à quel point il peut être fastidieux de les tester, à chaque nouvelle fonctionnalité ajoutée. Il existe bien les tests unitaires pour valider le code et les règles métier, les tests “golden” pour détecter les changements d’interface, mais tous ces tests sont statiques et ne permettent pas de valider une feature ou un parcours utilisateur dans l’application.</p><p>La pyramide de tests (expliquée pour Flutter dans <a href="https://medium.com/@a.poichet/flutter-et-la-pyramide-des-tests-avec-le-pattern-bloc-84dbe48f7f96">cet article</a> d’Alexandre Poichet avec Flutter), prévoit la mise en place de tests d’ “Intégration” et d’ “UI”. Mais si vous avez déjà eu à développer ce type de tests sur des applications natives, vous connaissez la difficulté à les maintenir, ainsi que le manque de fiabilité des résultats (notamment à cause des frameworks de test natifs).</p><blockquote>Dans cet article, je vais vous montrer comment nous avons développé, maintenu et utilisé les tests automatisés dans le processus de delivery continu de l’application SNCF Connect. SNCF Connect est un nouveau service digital, héritier de OUI.sncf, qui permet de planifier tous les trajets de courte et longue distance du 1er au dernier kilomètre.</blockquote><h3>Un peu d’histoire</h3><p>Avant SNCF Connect existaient OUI.sncf et L’Assistant, deux applications qui proposaient de réserver des trains, de rechercher un itinéraire porte-à-porte, de l’info-traffic… et ce partout en Europe. Ces applications étaient développées pour l’AppStore et le Google Play Store, en utilisant les frameworks natifs propres à chaque OS.</p><p>Les tests UI étaient également développés en utilisant les frameworks natifs de tests (XCTest pour iOS, Espresso pour Android). Ceci impliquait de devoir coder, tester et maintenir les tests sur chacune des plateformes. D’autres frameworks étaient disponibles, mais ils ne permettaient pas de tester des applications iOS.</p><p>Un autre point négatif concernant ces frameworks : leur manque de stabilité. Nous ne pouvions être sûrs d’avoir le même résultat, à l’issue de chaque exécution (et même si nous utilisions des bouchons/mocks des APIs). Pourquoi ? Plus votre application a un parcours complexe, plus vous rencontrez des animations, des appels réseaux… et les frameworks natifs gèrent mal de grosses applications.</p><p>Sur OUI.sncf, nous avions désactivé les animations et “mocké” les appels, mais nous avions toujours beaucoup d’instabilités liées à XCTest, lors de nos exécutions. Testeurs ou les jobs d’Intégration Continue devaient relancer le test, pour être sûrs de l’échec et de sa raison (et éviter les faux négatifs dus au Framework).</p><h3>Choisir la bonne pilule</h3><p>Pour SNCF Connect, nous avons étudié différents frameworks pour tester notre application Flutter. Notre évaluation s’est basée sur les critères suivants :</p><ul><li><strong>S</strong>tabilité : les résultats doivent être fiables (si le test échoue, la raison de l’échec doit être la même à chaque exécution)</li><li><strong>I</strong>ntégration : les tests doivent pouvoir s’exécuter indistinctement sur une machine locale ou sur la plateforme d’Intégration Continue</li><li><strong>R</strong>apport : les rapports de tests doivent être compréhensibles aussi bien par un développeur qu’un testeur</li><li><strong>I</strong>ntuitif : les tests doivent être simples à développer et maintenir</li></ul><p><em>Bonus : puisque nous développons à la fois une application pour iOS et Android, avoir également une base unique de code pour les tests serait un plus.</em></p><p>Grâce à notre expérience avec les frameworks natifs, nous savions que les frameworks natifs ne permettaient pas de satisfaire à notre exigence de stabilité.</p><p>Nous avons étudié plusieurs solutions et avons retenu Appium, mais pas leur SDK pour Flutter. En effet, au démarrage des développements de SNCF Connect, le driver Flutter Appium était encore en beta et beaucoup de fonctionnalités manquaient.</p><p>En parallèle, nous avons travaillé sur la manière dont nous souhaitions écrire et organiser nos tests. Sur OUI.sncf, nous avions éprouvé la combinaison Gherkin + Cucumber pour décrire nos tests backend (voir ici pour <a href="https://en.wikipedia.org/wiki/Cucumber_(software)">Gherkin/Cucumber</a>). Ce langage permet en effet d’améliorer la lisibilité des tests, les rend plus simples à comprendre pour un développeur ou un testeur. L’avantage d’un test Gherkin est qu’il décrit une fonctionnalité étape par étape, ce qui permet de rédiger au passage les spécifications fonctionnelles de l’application et du site Web. Ainsi pour SNCF Connect, nous utiliserions Gherkin pour écrire les étapes de nos tests, chaque test sera exécuté pour qualifier le Web, les applications mobiles et le BFF (<a href="https://samnewman.io/patterns/architectural/bff/">Back-For-Front</a>), si cela est pertinent.</p><p>Ainsi notre décision était claire : <strong>Appium + Cucumber</strong> (pour lire les Gherkins), en <strong>Kotlin</strong>. Kotlin s’imposait puisque notre backend (plus précisément notre BFF) est écrit en Kotlin. De plus, ce langage était déjà maîtrisé par les développeurs, et proche de Swift connu des développeurs iOS.</p><h3>Assembler les Lego</h3><p>Si vous n’avez jamais implémenté un test rédigé en Gherkin, Cucumber simplifie grandement l’intégration. En effet, Cucumber lit chaque étape (une étape étant l’interaction que réalise l’utilisateur avec l’interface, quelle qu’elle soit) d’un fichier .feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQVoylLXvPOGACChUl_xYQ.png" /><figcaption>Exemple de fichier .feature décrivant un Gherkin</figcaption></figure><p>Ensuite, Cucumber essaie de trouver la “glue” correspondante et exécute le code associé. Cette glue peut être la phrase exacte, ou une expression régulière :</p><pre>class WhenSteps {<br><br>    @Lorsque(&quot;(?i)^l&#39;utilisateur accède à l&#39;info trafic de la zone \&quot;(.+)\&quot;$&quot;)<br>    fun selectZone(zoneName: String) {<br>        TrafficInfoScreen.selectZone(zoneName)<br>    }<br>}</pre><p>Dans cet exemple, la glue repose sur une regex, qui vient rechercher les étapes qui débutent par la chaine, et qui utilise le “(.+)” pour extraire le paramètre, utilisé par la méthode associée. Si on regarde en détail cette méthode, on comprend qu’il s’agit d’un appel à une action d’un écran.</p><p>Pourquoi ce modèle ? Parce que nous avons mis en place le Pattern Page Object, pour concevoir l’architecture de notre code de test. Nous avions déjà utilisé ce pattern pour OUI.sncf, et il est toujours parfaitement adapté pour mettre en place les tests au format Gherkin avec Cucumber.</p><p>Il est d’autant plus puissant qu’il permet de décrire chaque écran (ou partie d’écran) au sein d’une classe, avec une méthode pour chaque action/interaction réalisable au sein du dit écran. Chaque action a ensuite la charge d’orienter le code de test vers le prochain écran du parcours.</p><p>Dans notre module de tests, nous avons mis en place une classe abstraite avec toutes les méthodes nécessaires au pattern :</p><pre>abstract class PageScreen {<br><br>    private val logger = KotlinLogging.logger <strong>{}<br>    </strong>private val modalErrorByElement = ByLocalizedTextAndClass(&quot;genericErrorTitle&quot;, Locators.viewClassName)<br>    private val backButtonByElement =<br>        ByLocalizedTextAndClass(&quot;accessibility_back_button&quot;, Locators.buttonClassName)<br><br>    abstract fun isScreenDisplayed(): Boolean<br><br>    fun activity(msg: String) {<br>        logger.info <strong>{<br>            </strong>this::class.toString().<em>replace</em>(packageName, &quot;&quot;).<em>replace</em>(&quot;class&quot;, &quot;&quot;).<em>trim</em>() + &quot; =&gt; &quot; + msg<br>        <strong>}<br>    </strong>}<br><br>    fun logError(msg: String) {<br>        logger.error <strong>{<br>            </strong>this::class.toString().<em>replace</em>(packageName, &quot;&quot;).<em>replace</em>(&quot;class&quot;, &quot;&quot;).<em>trim</em>() + &quot; =&gt; &quot; + msg<br>        <strong>}<br>    </strong>}<br><br>    fun checkIfErrorIsDisplayed(): PageScreen {<br>        if (doesScreenContainElement(modalErrorByElement, 15)) {<br>            logError(&quot;Une erreur de type inconnu s&#39;est produite&quot;)<br>            <em>fail</em>(&quot;Une erreur de type inconnu s&#39;est produite&quot;)<br>        }<br>        return this<br>    }<br><br>    fun goBackToPreviousScreen(): PageScreen {<br>        activity(&quot;Retour vers l&#39;écran précédent&quot;)<br>        Getters.getElementBy(backButtonByElement).click()<br>        return this<br>    }<br>}</pre><p>Comme on peut le voir, la classe fournit des fonctions, utiles pour naviguer au sein de l’application ou logger les commandes Appium, envoyées par le driver à l’émulateur/simulateur/mobile (ce qui couvre notre exigence de <strong>Rapport</strong>).</p><p>Arrêtons-nous un instant sur une méthode en particulier :</p><pre>abstract fun isScreenDisplayed(): Boolean</pre><p>Implémentée au sein de chaque classe, héritant de <em>PageScreen</em>, elle est nécessaire pour s’assurer que l’application affiche bien le bon écran, avant de permettre au test d’exécuter l’action suivante.</p><p>Le pattern Page Object et Gherkin/Cucumber simplifie également le développement et la maintenance de la base de code : coder une étape la rend disponible pour tous les cornichons qui l’utilisent. Changer le code (pour correspondre à un changement dans l’application) le met également à jour pour tous les tests. Et si vous envisagez d’apporter un changement plus important dans l’application (comme ajouter/supprimer un nouvel écran), il vous suffit de mettre à jour les étapes pour naviguer vers le nouvel écran, de coder la nouvelle interaction et d’enchaîner l’appel précédent effectué si nécessaire. Tout cela couvre notre exigence <strong>Intuitive</strong>.</p><h3>Côté code ?</h3><p>Comme indiqué précédemment, nous avons retenu Appium, pour interagir avec l’application. Appium fournit des méthodes pour sélectionner, faire défiler ou cliquer sur l’écran, comme le ferait un utilisateur.</p><p>Nous avons cependant développé nos propres méthodes, en sur-couche d’Appium :</p><pre><em>/**<br> * Return an element of the screen, using a By selector.<br> * </em><strong><em>@param </em></strong><em>selector way to select the object.<br> * </em><strong><em>@param </em></strong><em>secondsToWait timeout of max number of seconds to wait.<br> *<br> * </em><strong><em>@return </em></strong><em>MobileElement matching selector.<br> */<br></em>fun getElementBy(selector: By, secondsToWait: Long = SECONDS_TO_WAIT, maxNumberOfSwipes: Int = 5): MobileElement {<br>    logger.debug <strong>{ </strong>&quot;$selector, timeout : $secondsToWait&quot; <strong>}<br>    </strong>scrollTo(selector, maxNumberOfSwipes = maxNumberOfSwipes)<br>    waitForVisibility(selector, secondsToWait)<br>    return <em>driver</em>.findElement(selector) ?: <em>error</em>(&quot;Elément $selector non trouvé !&quot;)<br>}</pre><p>Cette méthode est utilisée pour rechercher un élément dans le DOM de l’application. Si aucun élément n’est trouvé, alors une erreur (incluant le sélecteur recherché) est loggée dans le rapport de test. Cela peut être un mauvais sélecteur codé, ou une véritable erreur applicative.</p><p>Voici comment nous utilisons cette méthode :</p><pre>private val stationsBoardBigLinesBnByElement = ByLocalizedTextAndClass(<br>    &quot;stationBoards.big.lines.label&quot;,<br>    <em>viewClassName</em></pre><pre>fun switchToBigLinesTab() {<br>    activity(&quot;Ouverture de l&#39;onglet Grandes lignes&quot;)<br>    getElementBy(stationsBoardBigLinesBnByElement).click()<br>}</pre><p>Tout d’abord, nous loggons l’action en cours, puis recherchons un élément et cliquons dessus.</p><p>Pour faire cette recherche :</p><pre>private val stationsBoardBigLinesBnByElement = ByLocalizedTextAndClass(<br>    &quot;stationBoards.big.lines.label&quot;,<br>    <em>viewClassName</em></pre><p>nous avons développé notre propre méthode :</p><pre>class ByLocalizedTextAndClass(<br>    accessibilityId: String,<br>    clazz: ByClassName,<br>    caseSensitive: Boolean = false,<br>    withoutAccent: Boolean = false,<br>    input: Map&lt;String, String&gt; = <em>emptyMap</em>()<br>) : ByTextAndClass(<br>    accessibilityId.<em>localize</em>(input),<br>    clazz,<br>    caseSensitive = caseSensitive,<br>    withoutAccent = withoutAccent<br>)</pre><p>Elle utilise 2 paramètres :</p><ul><li>l’<em>accessibilityId</em> (la chaine de caractères ou l’ID que nous souhaitons dans l’écran) : comme les IDs “réels” des objets changent dans l’application, ceci est le seul objet du DOM que nous maîtrisons.</li><li><em>className</em>: le type d’objet que nous cherchons. Ceci va permettre d’améliorer la vitesse de recherche dans l’arbre, en filtrant d’abord les objets par ce type, puis en cherchant le premier dont l’<em>accessibilityId</em> correspond</li></ul><p>Le className fourni est un alias vers le vrai type d’objet, dépendant du mobile sur lequel s’exécute le test :</p><pre>val viewClassName: ByClassName = when (<em>platform</em>) {<br>    <em>ANDROID </em>-&gt; ByClassName(&quot;android.view.View&quot;)<br>    <em>IOS </em>-&gt; ByClassName(&quot;XCUIElementTypeStaticText&quot;)<br>}</pre><p>Avec ces alias, il suffit de sélectionner le bon className pour trouver l’objet, sans tenir compte de la plateforme. De cette manière, nous développons directement le test pour iOS et Android, avec un seul code. Ceci couvre notre exigence <strong>Bonus</strong>.</p><p>Concernant les autres paramètres :</p><ul><li>caseSensitive : la recherche doit elle respecter les majuscules/minuscules</li><li>withoutAccent : la recherche doit elle tenir compte des accents</li><li>input : pour remplacer des chaînes contenant des paramètres</li></ul><p>Vous avez sans doute remarqué le terme <em>Localized</em> dans le nom de la méthode. Il est dû à l’utilisation des libellés (“wordings”) localisés dans nos tests. En effet, puisque la recherche d’un objet repose en partie sur son texte, via l’<em>accessibilityId</em>, il est plus pertinent de se baser sur une clé de wording fixe. Si un wording vient à changer dans l’application, aucune évolution de code n’est nécessaire (le fichier des libellés étant mutualisé entre le code applicatif et le code de test). De plus, le test développé peut également être utilisé pour tester l’application dans n’importe quelle langue supportée.</p><h3>Exécuter les tests</h3><p>Une fois le test et ses étapes développés, nous souhaitons l’exécuter à la fois pour vérifier qu‘il se déroule correctement, mais aussi pour vérifier qu’il couvre bien les exigences du Gherkin et la fonctionnalité concernée.</p><p>En utilisant Appium via Kotlin sur SNCF Connect, nous avons la possibilité de lancer un test sous forme de tâche gradle. Dans le module de tests, nous avons défini des configurations d’exécution dédiées aux IDEs de nos développeurs (IntelliJ, VSCode…) pour lancer un test ou un lot complet. Comment ? En utilisant des annotations :</p><pre>@mobile @sdk @web<br>  @IVTS-XXXXX @test_module</pre><p>Nous avons défini ces annotations pour décrire sur quelle plateforme le test peut s’exécuter, puisqu’un même Gherkin peut être utilisé pour un test, quel que soit l’OS.</p><p>Même si nous classons nos fichiers <em>feature</em> dans des répertoires dédiés, chacun correspondant à un module applicatif, nous avons mis en place une annotation au format @IVTS-XXXX, permettant d’identifier le test : IVTS étant le nom de code initial du projet, suivi du numéro de ticket Jira, dans lequel se trouve le Gherkin et les détails du test. Nous avons également mis en place l’annotation <em>@module_name</em> pour décrire le module testable via ce gherkin.</p><p>De cette manière, quand nous souhaitons tester une fonctionnalité, nous utilisons ces annotations pour lancer soit un test spécifique, soit tous les tests des modules impactés par la fonctionnalité.</p><p>L’exécution sur un poste de développement peut se faire de différentes manières, soit via les configurations d’IDE, soit en exécutant un script shell et la tâche gradle.</p><p>Ce script est également le même que celui exécuté sur notre plateforme d’Intégration Continue (ce qui couvre notre exigence d’<strong>Intégration</strong>).</p><h3>Tests automatisés et Intégration Continue</h3><blockquote>Nous n’aborderons ici en détail pas comment nous construisons/déployons le site Web, l’application, ou le BFF via notre Intégration Continue.</blockquote><p>SNCF Connect repose sur un “mono-repo” : tout le code de l’application, du site Web, du BFF, des Lambda (serverless), des tests, des autres assets et même l’Infra-as-Code se trouvent dans le dépôt Git, partagé par tous les développeurs.</p><p>À chaque changement fait sur ce répertoire, une Merge Request est ouverte et nous devons détecter les erreurs/régressions potentielles au plus tôt.</p><p>Pour cela, nous avons mis en place plusieurs jobs s’exécutant dans un même “pipeline de merge” : tests unitaires, tests golden, tests BFF et bien sûr les tests automatisés de parcours sur l’application et le site. Nous pouvons réduire le nombre de tests à exécuter, si la Merge Request n’impacte qu‘une plateforme spécifique (par ex. si le changement porte sur l’application, nous réduisons le volume des tests automatisés exécutés pour tester le site Web).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*CY_FypxmpADT8sL8ySnD3Q.png" /><figcaption>Jobs des tests automatisés</figcaption></figure><p>Comme on le voit sur cette capture d’un pipeline d’Intégration Continue, plusieurs jobs s’exécutent en parallèle, certains étant bloquant, d’autres non.</p><p><em>Remarque : ces tests couvrent plusieurs couches front-end et BFF, c’est pourquoi nous les appelons tests de bout-en-bout (« end-2-end » ou « e2e ») même si d’autres APIs back-office sont en revanche des mocks.</em></p><p>Durant l’étape de préparation :</p><ul><li>nous compilons le code des tests pour chaque plateforme</li><li>nous déployons une version de l’application sur SauceLabs, notre fournisseur de devices physiques (N.B. nous pouvons changer de fournisseur assez simplement, tant qu’il prend en charge le driver Appium).</li></ul><p>Durant l’étape d’exécution des tests :</p><ul><li>nous testons le BFF, pour nous assurer que les APIs sont toujours valides</li><li>nous testons l’application/site Web dans un environnement mocké. A l’heure actuelle, nous exécutons systématiquement un test, qui a une forte valeur métier</li></ul><p>Dans les prochaines semaines, nous ajouterons d’autres tests dans des jobs en Intégration Continue, avec nos cas d’utilisation les plus importants, afin de continuer à détecter les régressions éventuelles, au plus tôt.</p><h3>Bilan (et prochaines étapes)</h3><p>Depuis les débuts de nos développements pour SNCF Connect, nous avons pu faire de nombreux choix quant à nos tests auto, et ensuite éprouver ces choix pendant des mois.</p><p>Concernant Appium, le moins que l’on puisse dire, c’est que ce framework est stable : si un test échoue, il le fera systématiquement à la même étape pour la même raison (à chaque exécution dans le même environnement mocké), qu’il s’exécute sur la plateforme d’Intégration Continue ou une machine locale (satisfaisant ainsi notre exigences de <strong>Stabilité</strong>). Cela garantit la qualité des résultats de nos tests, et permet de reproduire une erreur sur une machine de développement et pour corriger rapidement un test si besoin. La stabilité d’Appium, ainsi que sa capacité à cibler iOS et Android avec le même code, a permis d’améliorer la fiabilité des résultats pour chaque plateforme et de mettre en place des rapports correspondant à nos besoins.</p><p>Ces tests auto nous ont permis de détecter des régressions dans l’application et le site Web via ses tests automatisés dédiés avant le déploiement en production, ce qui reste évidemment notre priorité, ainsi que des faiblesses dans l’architecture de notre plateforme d’Intégration Continue.</p><p>Même s’il nous a fallu des mois pour mettre en place une bibliothèque de tests avec un volume d’étapes et de parcours suffisant, développer de nouveaux tests est maintenant très rapide. Ajouter de nouvelles étapes est d’autant plus simple que notre surcouche d’Appium est dorénavant éprouvée. L’utilisation du pattern <em>Page Object</em> contribue également à la fluidité des développements et la maintenance des tests (par la possibilité de faire évoluer une étape, et de la rendre disponible pour toutes les autres tests).</p><p>Enfin, l’arrivée et la prise en main du projet par des nouveaux développeurs/testeurs est simplifiée, chaque test étant écrit en langage naturel (et en français).</p><p><em>Et la suite ?</em></p><p>Actuellement, nous en sommes à publier chaque semaine une nouvelle version majeure (incluant des fonctionnalités, pas seulement des correctifs) de l’application, du site Web et du BFF en production. Cela nous permet d’apporter plus de valeur plus fréquemment à nos utilisateurs, avec un « time-to-market » bien inférieur à celui que nous avions sur OUI.sncf. Ceci nécessite toutefois beaucoup d’attention et une charge importante, de tests de non-régression, pour les testeurs fonctionnels. Notre référentiel Jira étant connecté à XRay, nous travaillons à lancer des exécutions de tests XRay, directement depuis la plateforme d’Intégration Continue, pour tester des modules complets de l’application et du site Web via leurs annotations. Je reviendrai dans d’autres articles sur comment nous avons automatisé le processus complet de tests de Non Régression de l’application SNCF Connect.</p><p><em>Et vous ? Avez-vous déjà rencontré ces problèmes, ces enjeux ? Avez-vous des solutions à partager ? N’hésitez pas à nous contacter ou nous rejoindre pour travailler sur le sujet, nous cherchons des testeurs/automaticiens avec des offres d’emploi ouvertes en ce moment 😉</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e8aa471cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sncf-connect-tech/tester-automatiquement-une-application-flutter-77e8aa471cb">Tester automatiquement une application Flutter</a> was originally published in <a href="https://medium.com/sncf-connect-tech">SNCF Connect &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Tests of a Flutter application]]></title>
            <link>https://medium.com/@maxime.pontoire/automated-tests-of-a-flutter-application-3d878e9d8a61?source=rss-239b2b51e9d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d878e9d8a61</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[gherkin]]></category>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[mobile-test-automation]]></category>
            <dc:creator><![CDATA[Maxime Pontoire]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 15:26:36 GMT</pubDate>
            <atom:updated>2022-10-26T15:26:36.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTaqJMKllx6jVZ7b3uCAWg.png" /><figcaption>SNCF Connect developers are loving Flutter</figcaption></figure><h3>Introduction</h3><p>Many applications are now using the Flutter framework, to be available on iOS and Android (with the one code base). Since the last two years, the community has made the framework stable and has provided a lot of tools to test the code and the application. Within the same period, we’ve started to develop SNCF Connect, an application now used by millions people in France. Our ambition was to move to “continuous delivery” by using state of art solutions and automated tests.</p><p>If you have already made an application, you know how complicated it can be to test it, each time you’re adding a feature to it. You can write unit tests for the code, “golden” tests to check the changes in the UI, but theses tests are statics and are not validating the feature and navigation in the application.</p><p>To solve this issue, the pyramid of tests (check <a href="https://medium.com/@a.poichet/flutter-and-the-practical-test-pyramid-with-the-bloc-pattern-6e6bf10dda9d">this article</a> of Alexandre Poichet about the pyramid of tests with flutter) is providing I“ntegration tests” and “UI Tests”. But if you already have developed theses tests on native applications, you know how difficult it can be to maintain them, and trust their results when testing a complex application.</p><blockquote>This article will focus on how we managed to develop, maintain and use automated tests in the continuous delivery of SNCF Connect. SNCF Connect is a new digital service, inheriting from OUI.sncf, that can be used to plan a trip door-to-door.</blockquote><h3>A bit of history</h3><p>Before SNCF Connect were OUI.sncf and L’Assistant, two applications to book trains, search for a door-to-door itinerary buy, check trafic information, buy services… all over Europe. Theses applications were developed for AppStore and Google Play Store, using the native framework of each OS.</p><p>UI Tests were also developed using the native frameworks of UI Testing, provided by each OS (XCTest for iOS, Espresso for Android). This implied to code, test and maintain tests on each plateforme. Other frameworks like Appium were available, but not for testing an iOS app.</p><p>Moreover, theses framework were not stable: you couldn’t be sure to get the same results of an execution, each time you run the test. Why? Because, the more your app has a complexe route to test, the more you’re facing UI animation, network calls… and native frameworks are not working well on complex applications.</p><p>On OUI.sncf, we disabled UI animation and “mocked” the more we could, but on iOS, the XCTest framework failed inconsistently. Testers or CI jobs had to retry the test, in that case, so as to be sure of the failure (and avoid false negatives).</p><h3>Choosing the right pill</h3><p>With SNCF Connect, we tested several frameworks for the our Flutter app. The requirements were :</p><ul><li><strong>S</strong>tability: results should be reliable (if the test fails, the failure should be the same on every execution)</li><li><strong>I</strong>ntegration: tests had to run on local machine and CI</li><li><strong>R</strong>eporting: generated reports should be understandable for a developer or a tester</li><li><strong>I</strong>ntuitive: development of the test should be easy to start and maintain</li></ul><p><em>Bonus: since we are building an iOS and Android application, it would be great to have only basis of code to test both platforms.</em></p><p>Since we already had a lot of experience with natives testing frameworks, we knew that they couldn’t fulfill our requirement of stability.</p><p>We tried several solutions and moved to Appium, but not the Flutter version of the SDK. At the time we started SNCF Connect, the Appium Flutter Driver was still in beta and was lacking of feature.</p><p>In the meantime, we decided the way we wanted to write and organize our tests. On OUI.sncf, we tested Gherkin and Cucumber to describe the way we wanted to test our backend (more about <a href="https://en.wikipedia.org/wiki/Cucumber_(software)">Gherkin/Cucumber</a>). This language is making the test easier to understand, for developer and testers. In addition to that, when writing a Gherkin to describing a test step by step a functionality, we were also writing the specifications of our application (and website too). On SNCF Connect, we’ll use it to describe the steps of our tests, and a test will be used on web, mobile and BFF (<a href="https://samnewman.io/patterns/architectural/bff/">Back-For-Front</a>), if it is relevant.</p><p>So our final decision was clear: <strong>Appium + Cucumber</strong>, in <strong>Kotlin</strong>. Kotlin was the right language to use, since our backend (more precisely our BFF) was written in Kotlin. Moreover, Kotlin was already known by Android developers, and not that far from Swift, well known by iOS developers.</p><h3>Assembling Lego</h3><p>For those who have never implemented a test writin in Gherkin, Cucumber is making things really easy. Cucumber is reading each step (a step is describing the interaction a user will have with application) of a .feature file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQVoylLXvPOGACChUl_xYQ.png" /><figcaption>Gherkin Sample in one of our .feature files</figcaption></figure><p>Then, Cucumber tries to find the “glue” matching it and run the code linked to it. A glue is the exact sentence to match, or a regex :</p><pre>class WhenSteps {<br><br>    @Lorsque(&quot;(?i)^l&#39;utilisateur accède à l&#39;info trafic de la zone \&quot;(.+)\&quot;$&quot;)<br>    fun selectZone(zoneName: String) {<br>        TrafficInfoScreen.selectZone(zoneName)<br>    }<br>}</pre><p>Basically here, the glue is a regex matching the start of the sentence, and use the “(.+)” to extract the parameter used in the linked method. If you look what the code is doing, this method is only a call to an action on a screen.</p><p>Why? Because we’re using the Page Object Pattern to build up the architecture of the code. We already have used this pattern on OUI.sncf, and it was still perfectly adapted with Gherkin and Cucumber.</p><p>This Pattern is powerful, since each screen (or part of the screen) is described in its own class, with a method for each action/interaction available in it. Each action is returning the Page the app is moving too.</p><p>In our test module, we built an abstract class with all the required methods:</p><pre>abstract class PageScreen {<br><br>    private val logger = KotlinLogging.logger <strong>{}<br>    </strong>private val modalErrorByElement = ByLocalizedTextAndClass(&quot;genericErrorTitle&quot;, Locators.viewClassName)<br>    private val backButtonByElement =<br>        ByLocalizedTextAndClass(&quot;accessibility_back_button&quot;, Locators.buttonClassName)<br><br>    abstract fun isScreenDisplayed(): Boolean<br><br>    fun activity(msg: String) {<br>        logger.info <strong>{<br>            </strong>this::class.toString().<em>replace</em>(packageName, &quot;&quot;).<em>replace</em>(&quot;class&quot;, &quot;&quot;).<em>trim</em>() + &quot; =&gt; &quot; + msg<br>        <strong>}<br>    </strong>}<br><br>    fun logError(msg: String) {<br>        logger.error <strong>{<br>            </strong>this::class.toString().<em>replace</em>(packageName, &quot;&quot;).<em>replace</em>(&quot;class&quot;, &quot;&quot;).<em>trim</em>() + &quot; =&gt; &quot; + msg<br>        <strong>}<br>    </strong>}<br><br>    fun checkIfErrorIsDisplayed(): PageScreen {<br>        if (doesScreenContainElement(modalErrorByElement, 15)) {<br>            logError(&quot;Une erreur de type inconnu s&#39;est produite&quot;)<br>            <em>fail</em>(&quot;Une erreur de type inconnu s&#39;est produite&quot;)<br>        }<br>        return this<br>    }<br><br>    fun goBackToPreviousScreen(): PageScreen {<br>        activity(&quot;Retour vers l&#39;écran précédent&quot;)<br>        Getters.getElementBy(backButtonByElement).click()<br>        return this<br>    }<br>}</pre><p>As you can see, this class is providing helpers, used to navigate in the application or to log Appium commands sent with the driver to the emulator/device (which covers our <strong>Reporting</strong>).</p><p>But you may have noticed:</p><pre>abstract fun isScreenDisplayed(): Boolean</pre><p>Implemented in each class inheriting from <em>PageScreen</em>, this method is mandatory to be sure that we are on the right screen before moving to the next action.</p><p>The way we are building things with the Page Object Pattern and Gherkin/Cucumber makes it also very simple to develop or maintain our basis of code: coding a step makes it available for all gherkins using it. Changing the code into it (to match a change in the application) updates it also for all the tests. And if you consider making a bigger change in the application (like adding/removing a new screen), all you need to do is to update the steps to navigate to the new screen, code the new interaction and chain the previous call made if necessary. All of this cover our <strong>Intuitive</strong> requirement.</p><h3>Diving into the code</h3><p>As explained earlier, we chose to use Appium for interacting with our application. Appium is providing helpers to select, scroll and click in the application, like a real user would do.</p><p>We have developed our own methods based on Appium:</p><pre><em>/**<br> * Return an element of the screen, using a By selector.<br> * </em><strong><em>@param </em></strong><em>selector way to select the object.<br> * </em><strong><em>@param </em></strong><em>secondsToWait timeout of max number of seconds to wait.<br> *<br> * </em><strong><em>@return </em></strong><em>MobileElement matching selector.<br> */<br></em>fun getElementBy(selector: By, secondsToWait: Long = SECONDS_TO_WAIT, maxNumberOfSwipes: Int = 5): MobileElement {<br>    logger.debug <strong>{ </strong>&quot;$selector, timeout : $secondsToWait&quot; <strong>}<br>    </strong>scrollTo(selector, maxNumberOfSwipes = maxNumberOfSwipes)<br>    waitForVisibility(selector, secondsToWait)<br>    return <em>driver</em>.findElement(selector) ?: <em>error</em>(&quot;Elément $selector non trouvé !&quot;)<br>}</pre><p>This method is used to query the DOM of the application, to find a matching element. If no element is found, then an error (including the selector queried) is logged in the report. This could be either a bad selector coded, or a real error in the application.</p><p>Let’s see it in action:</p><pre>private val stationsBoardBigLinesBnByElement = ByLocalizedTextAndClass(<br>    &quot;stationBoards.big.lines.label&quot;,<br>    <em>viewClassName</em></pre><pre>fun switchToBigLinesTab() {<br>    activity(&quot;Ouverture de l&#39;onglet Grandes lignes&quot;)<br>    getElementBy(stationsBoardBigLinesBnByElement).click()<br>}</pre><p>This basically how a glue is working: first logging the action trying to be run, then using the helper to find and element and clicking on it.</p><p>Regarding the selector:</p><pre>private val stationsBoardBigLinesBnByElement = ByLocalizedTextAndClass(<br>    &quot;stationBoards.big.lines.label&quot;,<br>    <em>viewClassName</em></pre><p>We developed our on method:</p><pre>class ByLocalizedTextAndClass(<br>    accessibilityId: String,<br>    clazz: ByClassName,<br>    caseSensitive: Boolean = false,<br>    withoutAccent: Boolean = false,<br>    input: Map&lt;String, String&gt; = <em>emptyMap</em>()<br>) : ByTextAndClass(<br>    accessibilityId.<em>localize</em>(input),<br>    clazz,<br>    caseSensitive = caseSensitive,<br>    withoutAccent = withoutAccent<br>)</pre><p>2 parameters are required:</p><ul><li>the <em>accessibilityId</em> (which is the string/ID we’re looking on the screen): looking for it in the DOM is the only way we can find an object, since “real” IDs are changing</li><li><em>className</em>: the type of object we’re looking for: this will speed up the search by filtering first on the type, and then looking for the <em>accessibilityId.</em></li></ul><p>The className provided is an alias to real object type, depending on the platform running the test:</p><pre>val viewClassName: ByClassName = when (<em>platform</em>) {<br>    <em>ANDROID </em>-&gt; ByClassName(&quot;android.view.View&quot;)<br>    <em>IOS </em>-&gt; ByClassName(&quot;XCUIElementTypeStaticText&quot;)<br>}</pre><p>With theses aliases, we only need to use the right className to find the object, no matter the OS running the application. Thus, we’re developing a test for both iOS and Android, at the same time. This covers our <strong>Bonus</strong> requirement.</p><p>About the other optional parameters:</p><ul><li>caseSensitive: if we want the search to match using case</li><li>withoutAccent: if we want the search to get rid of accent</li><li>input: to replace string with params into it</li></ul><p>You may have noticed the term <em>Localized</em> in the method name. This is because we’re using localisation for our tests: since finding an object means finding is <em>accessibilityId</em> (aka its text), it’s easier to code a selector with a non-changing key. Even if the translated text is evolving, no change on the code is needed (again a better stability of the test and a simplicity of development). Plus, the test developed can be used to test any language supported.</p><h3>Running a test</h3><p>Once the test and its steps have been developed, we need to execute it. First, to see if the test is running like it should, then to check if the development made is satisfying the Gherkin and the functionality.</p><p>Using Appium for Kotlin on SNCF Connect enabled us to launch a test as a gradle task. In the test project, we defined configuration for IDEs (IntelliJ, VSCode) used by our developers to launch a specific test, or a full set.</p><p>How? by using annotations:</p><pre>@mobile @sdk @web<br>  @IVTS-XXXXX @test_module</pre><p>We defined annotations describing on which platform the test can be run, since as I said earlier, we chose to use the same Gherkin no matter the OS.</p><p>Then, even if our Gherkin in <em>feature</em> files are classified by directories, matching a module, we used @IVTS-XXXX annotation as a test ID: IVTS was the initial code name if the project followed by the number of the Jira entry where you can find more details about the test). We also developped an annotation <em>@module_name</em> to describe which module the test is about.</p><p>In that way, when testing a specific feature, we can use theses tags to launch and run either a specific test, or all the tests impacted by the new developments.</p><p>This execution can be run in several ways with a launch configuration in an IDE, as explained before, or using a shell script with a gradle task in it.</p><p>This script is the same running on our Continuous Integration (based on gitlab-ci (that covers our <strong>Integration</strong> point).</p><h3>Automated tests in Continuous Integration</h3><blockquote>I’ll not focus on how we build/deploy the website, the application, or the BFF on our CI.</blockquote><p>SNCF Connect is based on a mono-repo: all the code of the application, the website, the BFF, Lambdas (Serverless), tests and other assets (even Infra-as-Code) are on the same Git Repository, shared with all the developpers.</p><p>This implies that each time a change is made on it, a Merge Request is opened and we have to detect failure or regression as soon as possible.</p><p>To do that, several tests jobs are running in a “merge” pipeline: unit tests, golden tests, BFF tests and of course automated tests of the application and the website. We can lower the number of tests, if the merge request has only an impact on a specific platform (ex. not running automated tests on the website, if we’re only modifying the application).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*CY_FypxmpADT8sL8ySnD3Q.png" /><figcaption>Automated tests jobs</figcaption></figure><p>As you can see of this screen of a pipeline, several jobs (some of them are blocking) are running in parallel.</p><p><em>Theses tests are validating several layers of Front-end and BFF, that’s why we are naming them “end-2-end” tests, even if we’re mocking some external APIs.</em></p><p>Duration preparation step of the pipeline:</p><ul><li>we build the code of the tests for each platform</li><li>we deploy a built application to Saucelabs, our provider of real devices (N.B. we can change this provider easily and replace it with another service based on Appium Driver)</li></ul><p>During the test execution step of the pipeline:</p><ul><li>we test the BFF, to be sure that all of its APIs are still valides</li><li>we test the application/website with a mocked automated test. This test is the most common case, with high value for our business.</li></ul><p>In the next few weeks, we will add more tests to our CI job, with our top use cases, to detect potential regressions sooner.</p><h3>Conclusion (and next steps)</h3><p>Since the beginning of the development of SNCF Connect, we have made a lot of decisions regarding our automated tests, and have challenged them all along.</p><p>Regarding Appium, one great thing with it is that it’s very stable: if you have a failure on your test, it will fail the same way each time you run it (with the same mocked responses from the BFF), no matter running it on CI or on a local machine (that fulfills the <strong>Stability</strong> point).</p><p>Using Page Object pattern is making development/refinements easier. The stability of Appium, its ability to run tests either on iOS or Android, is also improving the reliability of the results on each platform directly, with our customized reporting.</p><p>Theses tests have helped to detect potential regressions in the app (and on the website too with its dedicated automated tests) and lacks in our CI architecture, before moving SNCF Connect to production, and making available to our millions of users.</p><p>Even if it took several months to have a large library of steps implemented, coding new ones is really fast now. Onboarding new developers and testers too, since tests are written in their native language, and implementing new steps means using stable helpers we developed above Appium.</p><p><em>What’s next?</em></p><p>We’re actually releasing a new version of the application each week (including features and not only fixes) of the application, the website and the BFF. Releasing at this pace is mandatory for us, to deliver continuously value to our customers (with a better “time-to-market” than with OUI.sncf). But, this implies a high workload for the functional testers. Since our Jira is connected to XRay, we plan to launch XRay executions, directly from our Continuous Integration platform, to test modules of the application or the website by using their tags.</p><p>Stay tuned here to see the updates about how we automatized the full process of non regression tests of SNCF Connect application.</p><p><em>And you? Have you ever faced theses problems? What were your solutions? Feel free to contact us or join us to work on this, we are looking for testers/automation specialists with open vacancies at the moment 😉</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d878e9d8a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>