<?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 Artur Korobeynyk on Medium]]></title>
        <description><![CDATA[Stories by Artur Korobeynyk on Medium]]></description>
        <link>https://medium.com/@arturkorobeynyk?source=rss-d1c2ea533ba6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7AK3alnGL1svwqu8mZfY5w.jpeg</url>
            <title>Stories by Artur Korobeynyk on Medium</title>
            <link>https://medium.com/@arturkorobeynyk?source=rss-d1c2ea533ba6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:16:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arturkorobeynyk/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[Collecting code coverage during the Flutter Driver test]]></title>
            <link>https://arturkorobeynyk.medium.com/collecting-code-coverage-during-the-flutter-driver-test-43a6d07229f6?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a6d07229f6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-driver]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Fri, 07 Oct 2022 23:25:16 GMT</pubDate>
            <atom:updated>2022-10-07T23:34:52.930Z</atom:updated>
            <content:encoded><![CDATA[<p>(this code uses an approach from the <a href="https://arturkorobeynyk.medium.com/running-flutter-driver-tests-with-an-already-running-application-b7ae63f5c35e">previous story</a> when Flutter Driver connects to an already running application)</p><p>The final source code is available here: <a href="https://github.com/arturk/basic_app">https://github.com/arturk/basic_app</a></p><p>So, let&#39;s get to the topic of code coverage with the Flutter Driver approach. It is very useful if you want to figure out whether your tests cover all the possible logical flows of the functionality.</p><p>In fact, it is very easy to build a code coverage solution with Flutter Driver.</p><p>We will utilize the Virtual Machine Service connection again. Basically, all we need to do is to get the data out of the Virtual Machine because it already is capable of collecting all that.</p><p>I will start by creating a simple flutter application with:</p><blockquote>flutter create basic_app</blockquote><p>It is necessary to add <strong>flutter_driver</strong> and <strong>test</strong> package dependencies to the <strong>pubspec.yaml</strong> file.</p><p>I will add the <strong>enableFlutterDriverExtension()</strong> call to the main function.</p><p>So now our app is ready for being used with flutter driver.</p><p>Now time for tests. First of all, I will use code from the previous story to write a function that can connect to an already running flutter application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*aNCVzwgO15NDNje8N-cLyg.png" /></figure><p>These are almost the same functions as were used in the previous article mentioned above. So you can read about those there.</p><p>Also, the latest Dart uses a slightly different for identifying the Observatory port in ADB logs. Instead of <strong>line.contains(‘Observatory’)</strong> you would do <strong>line.contains(‘Dart VM’)</strong>.</p><p>One difference here is using the <strong>Invoker.current!.addTearDown(_writeCoverageData)</strong> code.</p><p>_writeCoverageData function is a function that will collect and parse the source coverage information from the Dart VM service. We will define it later.</p><p><strong>Invoker.current!.addTearDown</strong> function call dynamically adds a tearDown function to the currently running test. So here it means, that if in a test setup we will use var driver = await initAdnroidFlutterDriver(); the teardown will be created automatically by the addTearDown function call and in teardown the logic of the _writeCoverageData function will be executed. Such an approach removes the necessity to write teardowns over and over again for each test and test suite across numerous files.</p><p>Next, we will create a function that will collect the source coverage data from virtual machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_ejbMqGCTgERnOSTyzJGOw.png" /></figure><p>This is also is going to be a teardown function</p><p>So, we are using <strong>getSourceReport</strong> function of the Dart VM service to retrieve the source coverage. It will return every bit of code that exists in the application but we are interested only in code that was compiled. So we filter out rest of the garbage. Next we make the json more convenient by adding path to the source file in place to every block of source code coverage report. And finally we are filtering out only the code that was written by us, meaning that we want to check only the code that is part of the <strong>basic_app</strong> package.</p><p>So now we need to run the test and check the source coverage during the test. The test would be as simple as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*ko_Pg3zNR_9MrnI7zOGkxw.png" /></figure><p>We have a setup where we use our custom driver initializer that will connect to the running flutter application. The initializer function will also create a hidden test teardown that will close the flutter driver when tests are over, write JSON coverage report.</p><p>Source_coverage.json will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*uTkFN9OF6GqRH5O6_rATWQ.png" /></figure><p>Here starPos and endPos point to code block start and end positions (bytes within file). While hits and misses in the coverage report show executed or skipped lines of code within the file starting from index 1. scriptUri is a path to the file that we added when parsing coverage json from Dart VM.</p><p>But we can go further and make a human-readable HTML page of the json by parsing the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*4WtwZbuLltzov1Ckb3i0mw.png" /></figure><p>So, after running the test we will have two files — JSON report of the source coverage and an HTML file showing which lines were executed and which were skipped:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Q5XJMbq9t3yLDrZHS3xY1Q.png" /></figure><p>Video example of running the application, testing, and getting source coverage report from this code is available here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FI9xuX0nIVYI&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DI9xuX0nIVYI&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/690fec9ee8b52e16c118f2a52863265f/href">https://medium.com/media/690fec9ee8b52e16c118f2a52863265f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a6d07229f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running flutter driver tests with an already running application]]></title>
            <link>https://arturkorobeynyk.medium.com/running-flutter-driver-tests-with-an-already-running-application-b7ae63f5c35e?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ae63f5c35e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-driver]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[observatory]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 10:04:41 GMT</pubDate>
            <atom:updated>2022-09-19T10:10:06.618Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have a complex application often you will need to run your tests within the application that is already staying in some kind of state by this time. With the flutter integration tests package, it is not possible (or at least I did not figure out yet how to do that). You always need to start your tests along with launching the application. But flutter driver is capable of being attached to an already running application, so that means that your tests can switch between different programming languages and environments while being executed to bring the application to the necessary state, and then you can attach your flutter driver to that app and start your dart tests.</p><p>Here is how it is done. Let&#39;s start by creating a simple application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*YlTiAqrnQsZGX9tIR6mHFQ.png" /></figure><p>Let&#39;s now run the application using the</p><blockquote><strong>flutter run</strong></blockquote><p>For this tutorial, I am running the application in a mobile device. Flutter will start executing the dart code and for that it will create a Dart Virtual Machine capable of executing the compiled dart code. The virtual machine will stay active for as long as application is running. If application is started in debug or profiling mode, the virtual machine will expose a URL that can be used to connect to it for checking the application behavior and debugging. Check the ADB logs after the app has started</p><blockquote><strong>adb logcat -d | less</strong></blockquote><p>Search for the line containing ‘<em>The Dart VM service is listening on</em>’. This line will contain URL, port and token that can be used to connect to the dart virtual machine. Because Dart VM is running on the Android mobile device at the moment, in order to access that URL and port we first need to adb forward that. Run in the command line:</p><blockquote><strong>adb forward tcp:&lt;port number&gt; tcp:&lt;port number&gt;</strong></blockquote><p>Where &lt;port number&gt; is a port that you got from the adb logcat.</p><p>Now you can paste the whole URL from the adb logcat into your browser and you will be able to access the Dart observatory tool that is a Dart debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*H8yT5pMPLNq1FZl8XvZqJw.png" /></figure><p>You can play with it but the main point is that we should be able to access it. Flutter driver uses the same URL to connect to the Observatory to be able to execute its commands. The same VM is used by Flutter Dev Tools to provide developers with a piece of more pretty information regarding the running dart application.</p><p>But our application is not yet ready for the flutter driver. Do you remember that we need to add a server, flutter driver extension, that will listen to the test commands within the application’s isolate process? To do that, we need to add dev dependencies to our application in pubspec.yaml file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*3Vzfn1IYEIVyhgosDSL2JQ.png" /></figure><p>Now we can enable the flutter driver extension in the application. I will do it right away in a current main file for this tutorial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*-e2VmAlU6i8kG-Kw-NyrHQ.png" /></figure><p>Now if you run the application, nothing should be changed for you from the application UI perspective but it will contain a listener process that can be used by Flutter Driver to send commands to the application through the Observatory dart debugger.</p><p>Now let&#39;s write a flutter driver test. The old tutorials tell you to create tests in specific folders with specific names. That is not something that I call flexible. Instead of the old way, we will do it in another way.</p><p>FlutterDriver.connect named constructor for Flutter Driver accepts a named parameter dartVmServiceUrl:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*-pJxGwS8qd2_zVWnHsLoOw.png" /></figure><p>It can be used to specify where Flutter Driver should connect to the dart virtual machine. Meaning, that the application may be already running somewhere and you can just point your test file to connect to that application and run test there. To get that URL for the flutter driver you need to get the Dart VM URL from the adb logcat as we did before, replace the ‘http’ protocol in the URL with the ‘ws’ protocol and append the URL with ‘/ws’. So, the final URL would be something like this:</p><blockquote><a href="http://127.0.0.1:43781/959LBNiPG5c=/#/vm-connect">ws://127.0.0.1:43781/959LBNiPG5c=/</a>ws</blockquote><p>For that we can create a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NJw1zcpRmAfIv7o0V4B2g.png" /></figure><p>So it does the same, gets the line with the Dart VM connection, parses it, forwards ports, and returns connection parameters.</p><p>Now we can create our flutter driver factory for example like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArbEpITTKjIgxR7f0TtrJA.png" /></figure><p>After it is done, we can write our test in the same way as we would do in a regular Flutter Driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*lVmnGSXIWtADd3G_YbV7Xw.png" /></figure><p>And now you are not bound to any rules except your application must be running already by the time your tests are started. Your tests will automatically get the necessary connection parameters from the ADB logcat and run the flutter driver test for that application.</p><p>The same can be done for a web browser-based application. But for that, you will need to create a web driver instance in dart code, get the session id, URI, specs from it and then use those in WebFlutterDriver.connectedTo function. For example, in a function below I get web driver connection parameters from environment variables that are set by running another test that uses Python to create a browser, run through the web app part until it gets to the Flutter Web App and then Python triggers a test that will use the function below to connect Web Flutter Driver to the Web Application written with flutter that is by this time is running in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goISVEflsmq81W_HXNv-7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ae63f5c35e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using commands to query flutter driver for widgets states and properties]]></title>
            <link>https://arturkorobeynyk.medium.com/using-commands-to-query-flutter-driver-for-widgets-states-and-properties-c7a5a18fea42?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7a5a18fea42</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-driver]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 14:52:30 GMT</pubDate>
            <atom:updated>2021-04-05T14:52:30.891Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story we will use a basic template flutter application to see how flutter driver is used to test that application, what are driver limitations with basic setup and how to go beyound those and unlock all driver capabilities.</p><p>First of all we need to create a new project. Run the next command in your terminal:</p><pre>flutter create beyound_flutter_driver</pre><p>This will create a basic project with all the necessary files. Navigate into folder with a newly created project and open it with visual code running code . inside it.</p><p>Replace lib/main.dart code with this:</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>    );<br>  }<br>}</pre><pre>class MyHomePage extends StatefulWidget {<br>  MyHomePage({Key key, this.title}) : super(key: key);<br>  final String title;</pre><pre><a href="http://twitter.com/override">@override</a><br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}</pre><pre>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  int _counter = 0;<br>  bool _isButtonDisabled;</pre><pre>void incrementCounter() {<br>    setState(() {<br>      _isButtonDisabled = true;<br>      _counter++;<br>      _isButtonDisabled = false;<br>    });<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  void initState() {<br>    super.initState();<br>    _isButtonDisabled = false;<br>  }</pre><pre>Widget _buildCounterButton() {<br>    return new ElevatedButton(<br>      child: new Text(&quot;Increment&quot;),<br>      onPressed: _isButtonDisabled ? null : incrementCounter,<br>      key: ValueKey(&#39;increment&#39;),<br>    );<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Text(<br>              &#39;You have pushed the button this many times:&#39;,<br>            ),<br>            Text(<br>              &#39;$_counter&#39;,<br>              key: ValueKey(&#39;counter&#39;),<br>              style: Theme.of(context).textTheme.headline4,<br>            ),<br>            _buildCounterButton(),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Open the pubspec.yaml file and change its dev_dependencies to:</p><pre>dev_dependencies:<br>  flutter_driver:<br>    sdk: flutter<br>  test: any</pre><p>Create new test_driver folder in the project and app.dart file inside it</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:beyound_flutter_driver/main.dart&#39; as app;</pre><pre>void main() {<br>  enableFlutterDriverExtension();<br>  app.main();<br>}</pre><p>Add test_driver/app_test.dart file with content:</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;<br>import &#39;package:test/test.dart&#39;;</pre><pre>void main() {<br>  group(&#39;Counter App&#39;, () {<br>    final counterTextFinder = find.byValueKey(&#39;counter&#39;);<br>    final buttonFinder = find.byValueKey(&#39;increment&#39;);</pre><pre>FlutterDriver driver;</pre><pre>setUpAll(() async {<br>      driver = await FlutterDriver.connect();<br>    });</pre><pre>setUp(() async {<br>      startingCounter = int.parse(await driver.getText(counterTextFinder));<br>    });</pre><pre>tearDownAll(() async {<br>      if (driver != null) {<br>        driver.close();<br>      }<br>    });</pre><pre>test(&#39;starts at 0&#39;, () async {<br>      expect(await driver.getText(counterTextFinder), &quot;0&quot;);<br>    });</pre><pre>test(&#39;increments the counter&#39;, () async {<br>      await driver.tap(buttonFinder);<br>      expect(await driver.getText(counterTextFinder), &quot;1&quot;);<br>    });<br>  });<br>}</pre><p>In Android Studio open the AVD Manager (Simulator in iOS) Tools -&gt; AVD Manager, add new android (iOS)device if necessary and start it. To run the tests execute following command:</p><pre>flutter drive --target=test_driver/app.dart</pre><p>At this point all tests should pass as there is nothing complicated in this example.</p><p>Now lets add another test which will add some more values:</p><pre>test(&#39;increment the counter many times&#39;, () async {<br>      for (var i = startingCounter + 1; i &lt; startingCounter + 5; i++) {<br>        await driver.tap(buttonFinder);<br>        expect(await driver.getText(counterTextFinder), i.toString());<br>      }<br>    });</pre><p>Run tests again and check that everything works fine once again.</p><p>Now lets add a bit of real logic simulation. When we press increment button there will be some logic hidden behind it. And while it executes we want our increment button to become disabled so user will not be able to add new value while current is still being added. Change the incrementCounter to:</p><pre>void incrementCounter() {<br>    setState(() {<br>      _isButtonDisabled = true;<br>      _counter++;<br>      Future.delayed(Duration(seconds: 1)).whenComplete(() =&gt; setState(() {<br>            _isButtonDisabled = false;<br>          }));<br>    });<br>  }</pre><p>Now try to run tests again. You will see that tests are failing. This is happening because we are clicking Increment button while it is disabled. There is no function in flutter driver to wait for enabled button. And many testers at this point start to either:</p><p>a) sleep and tap</p><p>b) tap and wait for text to appear, if not tap once again</p><p>But starting from flutter version 2 it is possible to implement custom commands. So lets make one that is capable to retrieve button state.</p><p>First we need to create a custom command description file. Create file lib/custom_commands.dart</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;</pre><pre>enum ButtonState { enabled, disabled }</pre><pre>class GetButtonStateCommand extends CommandWithTarget {<br>  GetButtonStateCommand(SerializableFinder finder, {Duration timeout})<br>      : super(finder, timeout: timeout);</pre><pre>GetButtonStateCommand.deserialize(<br>      Map&lt;String, String&gt; json, DeserializeFinderFactory finderFactory)<br>      : super.deserialize(json, finderFactory);</pre><pre><a href="http://twitter.com/override">@override</a><br>  Map&lt;String, String&gt; serialize() {<br>    return super.serialize();<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  String get kind =&gt; &#39;GetButtonState&#39;;<br>}</pre><pre>class GetButtonStateCommandResult extends Result {<br>  const GetButtonStateCommandResult(this.result);</pre><pre>final ButtonState result;</pre><pre>GetButtonStateCommandResult.fromJson(Map&lt;String, dynamic&gt; json)<br>      : this.result = ButtonState.values<br>            .firstWhere((value) =&gt; value.index == json[&#39;state&#39;]);</pre><pre><a href="http://twitter.com/override">@override</a><br>  Map&lt;String, int&gt; toJson() {<br>    return &lt;String, int&gt;{<br>      &#39;state&#39;: result.index,<br>    };<br>  }<br>}</pre><p>Now we can make implementation of this custom command. Create file lib/custom_commands_extension.dart</p><p>Now paste this content into it:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:flutter_driver/flutter_driver.dart&#39; show Command, Result;<br>import &#39;custom_commands.dart&#39;;</pre><pre>class GetButtonStateCommandExtension extends CommandExtension {<br>  <a href="http://twitter.com/override">@override</a><br>  String get commandKind =&gt; &#39;GetButtonState&#39;;</pre><pre><a href="http://twitter.com/override">@override</a><br>  Future&lt;Result&gt; call(<br>      covariant GetButtonStateCommand command,<br>      WidgetController prober,<br>      CreateFinderFactory finderFactory,<br>      CommandHandlerFactory handlerFactory) async {<br>    final Finder finder = finderFactory.createFinder(command.finder);<br>    // wait until widget is present on the screen<br>    await handlerFactory.waitForElement(finder);<br>    //check that widget is a button<br>    var btn = prober.widget(finder) as ElevatedButton;<br>    return btn.enabled<br>        ? GetButtonStateCommandResult(ButtonState.enabled)<br>        : GetButtonStateCommandResult(ButtonState.disabled);<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  Command deserialize(<br>      Map&lt;String, String&gt; params,<br>      DeserializeFinderFactory finderFactory,<br>      DeserializeCommandFactory commandFactory) {<br>    return GetButtonStateCommand.deserialize(params, finderFactory);<br>  }<br>}</pre><p>This is very raw implementation but it is done to make the understanding easier. It has some flaws but those are not the point of this tutorial.</p><p>Now we need to turn on this command in our tests. Change test_driver/app.dart file to this:</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:beyound_flutter_driver/custom_commands_extension.dart&#39;;<br>import &#39;package:beyound_flutter_driver/main.dart&#39; as app;</pre><pre>void main() {<br>  enableFlutterDriverExtension(commands: [GetButtonStateCommandExtension()]);<br>  app.main();<br>}</pre><p>By doing this we enabled new command extension in our flutter driver extension so now we can send this command from tests to application. Update tests to match the following:</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;<br>import &#39;package:test/test.dart&#39;;<br>import &#39;package:beyound_flutter_driver/custom_commands.dart&#39;;</pre><pre>Future&lt;void&gt; waitForButtonState(<br>    FlutterDriver driver, SerializableFinder finder, ButtonState state) async {<br>  var btnState;<br>  while (btnState != state) {<br>    btnState = GetButtonStateCommandResult.fromJson(<br>      await driver.sendCommand(GetButtonStateCommand(finder)),<br>    ).result;<br>    await Future.delayed(Duration(milliseconds: 200), () =&gt; {});<br>  }<br>}</pre><pre>void main() {<br>  group(&#39;Counter App&#39;, () {<br>    final counterTextFinder = find.byValueKey(&#39;counter&#39;);<br>    final buttonFinder = find.byValueKey(&#39;increment&#39;);</pre><pre>FlutterDriver driver;<br>    int startingCounter;</pre><pre>setUpAll(() async {<br>      driver = await FlutterDriver.connect();<br>    });</pre><pre>setUp(() async {<br>      startingCounter = int.parse(await driver.getText(counterTextFinder));<br>    });</pre><pre>tearDownAll(() async {<br>      if (driver != null) {<br>        driver.close();<br>      }<br>    });</pre><pre>test(&#39;starts at 0&#39;, () async {<br>      expect(await driver.getText(counterTextFinder), &quot;0&quot;);<br>    });</pre><pre>test(&#39;increments the counter&#39;, () async {<br>      await driver.tap(buttonFinder);<br>      expect(await driver.getText(counterTextFinder), &quot;1&quot;);<br>    });</pre><pre>test(&#39;increment the counter many times&#39;, () async {<br>      for (var i = startingCounter + 1; i &lt; startingCounter + 5; i++) {<br>        await waitForButtonState(driver, buttonFinder, ButtonState.enabled);<br>        await driver.tap(buttonFinder);<br>        expect(await driver.getText(counterTextFinder), i.toString());<br>      }<br>    });<br>  });<br>}</pre><p>Now if you run test it will pass again and clicks will happen only when button becomes enabled.</p><p>In the same way you can query for text fonts, colors, sizes, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a5a18fea42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using custom finders and custom commands with flutter driver extension (advanced level)]]></title>
            <link>https://arturkorobeynyk.medium.com/using-custom-finders-and-custom-commands-with-flutter-driver-extension-advanced-level-44df0286922b?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/44df0286922b</guid>
            <category><![CDATA[flutter-driver]]></category>
            <category><![CDATA[flutter-test]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 00:43:38 GMT</pubDate>
            <atom:updated>2021-03-15T09:03:03.854Z</atom:updated>
            <content:encoded><![CDATA[<p>While working with flutter driver extension in the flutter version 1.25 while it still was in beta I noticed two interesting parameters that can be passed to enableFlutterDriverExtension function. Those are finders and commands. Those parameters are now in stable version of flutter 2 but still are described poorly and did not find any documentation or examples in the wild on how to use those. So I tried to figure out on how to use those myself.</p><p>The source code comments regarding those params are lacking proper documentation on how to use those at the moment and does not provide working examples but still I was able to implement this feature and it is awesome.</p><p>As you know at the moment there are very few types of finders in flutter driver (byType, byText, byValueKey, etc). But there are even fewer commands that you can do with those (tap, enterText, maybe smth else). So using this approach you can extend those without limits.</p><p>Here I continue to work with app and tests from previous lessons. It is a basic app that is created when you start new flutter project, the one that increases counter text every time you press + button. The is a single source code for the app and tests within it and it is available here: <a href="https://github.com/arturk/flutter_driver_tutorials/tree/custom_finder_commands">https://github.com/arturk/flutter_driver_tutorials/tree/custom_finder_commands</a> .Within the source code of that app I created a folder for new finders: lib/finders . Within that folder I first created finders file that creates a new finder for the FloatingActionButton type as well as a new command that will use this finder. The finder will find a single instance of the FloatingActionButton. And the new command will Tap FloatingActionButton specified number of times. This file basically does not contain any working functionality. It serves only to describe the finder and command, like how those are called (finderType is passed to driver extension for finder and kind for command), how those should be serialized to be sent to the flutter driver extension and how those should be deserialized to populate all own parameters. Also this file contains structure of the new commands.</p><p>Finder:</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;</pre><pre>class FloatingActionButtonFinder extends SerializableFinder {<br>  const FloatingActionButtonFinder();</pre><pre><a href="http://twitter.com/override">@override</a><br>  String get finderType =&gt; &#39;FloatingActionButtonFinder&#39;;</pre><pre><a href="http://twitter.com/override">@override</a><br>  Map&lt;String, String&gt; serialize() =&gt; super.serialize();<br>}</pre><p>Command:</p><pre>class FloatingActionButtonCommand extends CommandWithTarget {<br>  FloatingActionButtonCommand(SerializableFinder finder, this.times,<br>      {Duration timeout})<br>      : super(finder, timeout: timeout);</pre><pre>FloatingActionButtonCommand.deserialize(<br>      Map&lt;String, String&gt; json, DeserializeFinderFactory finderFactory)<br>      : times = int.parse(json[&#39;times&#39;]),<br>        super.deserialize(json, finderFactory);</pre><pre><a href="http://twitter.com/override">@override</a><br>  Map&lt;String, String&gt; serialize() {<br>    return super.serialize()..addAll(&lt;String, String&gt;{&#39;times&#39;: &#39;$times&#39;});<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  String get kind =&gt; &#39;FloatingActionButtonCommand&#39;;</pre><pre>final int times;<br>}</pre><pre>class FloatingActionButtonCommandResult extends Result {<br>  const FloatingActionButtonCommandResult(this.result);</pre><pre>final String result;</pre><pre><a href="http://twitter.com/override">@override</a><br>  Map&lt;String, dynamic&gt; toJson() {<br>    return &lt;String, dynamic&gt;{<br>      &#39;result&#39;: result,<br>    };<br>  }<br>}</pre><p>Now when we have finished describing our new finders and commands we can create a file that will implement functionality for those. I placed it in lib/finders/finders_extension.dart .</p><p>This file should import the previously created file. It will map commands to commands extension using its commandKind parameter and kind parameter from previous file. finderType will be matched to the param with the same name. The createFinder function should return true or false. true should be returned when your find predicate succeeds with some widget. In my case I returned true as soon as element linked to widget of type FloatingActionButton was found.</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_driver/flutter_driver.dart&#39;<br>    show SerializableFinder, Command, Tap, Result;<br>import &#39;finders.dart&#39;;</pre><pre>class FloatingActionButtonFinderExtension extends FinderExtension {<br>  String get finderType =&gt; &#39;FloatingActionButtonFinder&#39;;</pre><pre>SerializableFinder deserialize(<br>      Map&lt;String, String&gt; params, DeserializeFinderFactory finderFactory) {<br>    return FloatingActionButtonFinder();<br>  }</pre><pre>Finder createFinder(<br>      SerializableFinder finder, CreateFinderFactory finderFactory) {<br>    return find.byElementPredicate((Element element) {<br>      if (element.widget is FloatingActionButton) {<br>        return true;<br>      }<br>      return false;<br>    });<br>  }<br>}</pre><p>You command extension will use the finder within its call function to execute your logic for that element. In my case I Tap times number of times on that element.</p><pre>class FloatingActionButtonCommandExtension extends CommandExtension {<br>  <a href="http://twitter.com/override">@override</a><br>  String get commandKind =&gt; &#39;FloatingActionButtonCommand&#39;;</pre><pre><a href="http://twitter.com/override">  @override</a><br>  Future&lt;Result&gt; call(<br>      Command command,<br>      WidgetController prober,<br>      CreateFinderFactory finderFactory,<br>      CommandHandlerFactory handlerFactory) async {<br>    final FloatingActionButtonCommand someCommand = command;</pre><pre>    final Finder finder = finderFactory.createFinder(someCommand.finder);<br>    await handlerFactory.waitForElement(finder);<br>    for (int index = 0; index &lt; someCommand.times; index++) {<br>      await handlerFactory.handleCommand(<br>          Tap(someCommand.finder), prober, finderFactory);<br>    }</pre><pre>    return FloatingActionButtonCommandResult(<br>        &#39;Tapped ${someCommand.times} times&#39;);<br>  }</pre><pre><a href="http://twitter.com/override">@override</a><br>  Command deserialize(<br>      Map&lt;String, String&gt; params,<br>      DeserializeFinderFactory finderFactory,<br>      DeserializeCommandFactory commandFactory) {<br>    return FloatingActionButtonCommand.deserialize(params, finderFactory);<br>  }<br>}</pre><p>Now in order to use these you need to enable your flutter driver extension in such way:</p><pre>void main() {<br>  enableFlutterDriverExtension(<br>      handler: dataHandlerFunction,<br>      commands: [FloatingActionButtonCommandExtension()],<br>      finders: [FloatingActionButtonFinderExtension()]);<br>  app.main();<br>}</pre><p>Here I also use my dataHandlerFunction from previous articles but that one is not important for this topic.</p><p>Because one part of the finder is used in testing side (finder) and the other part is used in app side (finder extension) the finders and commands declared in such approach should be done as packages so they can be imported using pubspec.yaml and used both — in app and in tests while having single code base.</p><p>Now finally I would write tests like:</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;<br>import &#39;package:test/test.dart&#39;;<br>import &#39;package:testing_tutorial/finders/finders.dart&#39;;</pre><pre>void main() {<br>  group(&#39;Counter App&#39;, () {<br>    final counterTextFinder = find.byValueKey(&#39;counter&#39;);<br>    FlutterDriver driver;</pre><pre>setUpAll(() async {<br>      driver = await FlutterDriver.connect();<br>    });</pre><pre>tearDownAll(() async =&gt; driver?.close());</pre><pre>test(&#39;increments using custom commands by 5&#39;, () async {<br>      final expected = int.parse(await driver.getText(counterTextFinder)) + 5;<br>      await driver.sendCommand(FloatingActionButtonCommand(<br>          FloatingActionButtonFinder(), 5,<br>          timeout: Duration(seconds: 10)));<br>      final actual = int.parse(await driver.getText(counterTextFinder));<br>      expect(actual, equals(expected));<br>    });<br>  });<br>}</pre><p>And that is it! Using this method you can actually replace all your dataHandler functionality from flutter driver extension. You can create finders for all your custom widgets. And you can create custom commands for anything that you want to check: widget properties, custom application state changes, code injections, etc!</p><p>You can checkout the code from the <a href="https://github.com/arturk/flutter_driver_tutorials/tree/custom_finder_commands">github </a>and try to run it using:</p><pre>flutter drive --target=test_driver/driver.dart</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44df0286922b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using gestures within data handler function of flutter driver extension]]></title>
            <link>https://arturkorobeynyk.medium.com/using-gestures-within-data-handler-function-of-flutter-driver-extension-6b4347be4b7c?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b4347be4b7c</guid>
            <category><![CDATA[flutter-driver]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 19:33:42 GMT</pubDate>
            <atom:updated>2021-03-11T19:33:42.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes you need to test event related to mouse movements within your E2E tests. Flutter driver does not provide yet native functionality for this activities but you can write your own within data handler function of the enableFlutterDriverExtension() function call.</p><p>First of all you will need to find element that points to the widget over which you want to perform a mouse move event. You can use collectAllElementsFrom function from flutter_test package for that.</p><pre>final element = collectAllElementsFrom(<br>    WidgetsBinding.instance.renderViewElement,<br>    skipOffstage: false)<br>    .firstWhere((element) =&gt;<br>    element.widget.key.toString().contains(yourSearchedValueKey));</pre><p>Having the element you can get its render box which will give you access to the widget coordinates and size:</p><pre>final RenderBox box = element.renderObject as RenderBox;<br>final centerOfTheWidgetOffset =<br>    box.localToGlobal(box.size.center(Offset.zero));</pre><p>To create a movement action we will need to tell our function where to move pointer to. Lets pretend that we need to stay within the widget and move the pointer diagonally from center to its corner. The movement vector will point to this direction:</p><pre>var moveOffset = Offset(box.size.width / 2, box.size.height / 2);</pre><p>Now it is time to create something that is called a gesture in Flutter. Gesture is an action that you do with your input device (touchscreen, mouse, keyboards, etc). You will need packages flutter/widgets.dart,flutter/gestures.dart for that. Gestures are created using WidgetController, which is something that deals with actions related to widgets. But because we pretend to control widgets not during widget tests but within live application using flutter driver we need to use LiveWidgetController.</p><pre>final wc =<br>    LiveWidgetController(WidgetsFlutterBinding.ensureInitialized());<br>final gesture = await wc.createGesture(kind: PointerDeviceKind.mouse); // this gesture will be simulating mouse<br>await gesture.moveTo(centerOfTheWidgetOffset);<br>await gesture.moveBy(moveOffset);</pre><p>And that is all. You function is ready. Here is how the full code of the handler function will look like:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:flutter/gestures.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;</pre><pre>Future&lt;String&gt; dataHandler(String payload) async {<br>  if(payload == &quot;moveMouseGesture&quot;){<br>    final element = collectAllElementsFrom(<br>        WidgetsBinding.instance.renderViewElement,<br>        skipOffstage: false)<br>      .firstWhere((element) =&gt;<br>        element.widget.key.toString()<br>          .contains(yourSearchedValueKey));<br>    final RenderBox box = element.renderObject as RenderBox;<br>    final centerOfTheWidgetOffset =<br>        box.localToGlobal(box.size.center(Offset.zero));<br>    var moveOffset =<br>        Offset(box.size.width / 2, box.size.height / 2);<br>    final wc = LiveWidgetController(<br>        WidgetsFlutterBinding.ensureInitialized());<br>    final gesture = await wc.createGesture(<br>        kind: PointerDeviceKind.mouse);<br>    await gesture.moveTo(centerOfTheWidgetOffset);<br>    await gesture.moveBy(moveOffset);<br>    return jsonEncode({<br>        &quot;movedFrom&quot;: centerOfTheWidgetOffset.toString(),<br>        &quot;movedBy&quot;: moveOffset.toString()});<br>  }<br>}<br>...<br>  enableFlutterDriverExtension(handler: dataHandler);</pre><p>Now from the tests you can execute this command:</p><pre>FlutterDriver driver = ...;<br>await driver.requestData(&quot;moveMouseGesture&quot;);</pre><p>And that will simulate the mouse move event over the necessary widget within app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b4347be4b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using browser console to interact with web flutter driver + chrome extension for flutter driver]]></title>
            <link>https://arturkorobeynyk.medium.com/using-browser-console-to-interact-with-web-flutter-driver-chrome-extension-for-flutter-driver-6045785b15b5?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6045785b15b5</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-driver]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 21:40:19 GMT</pubDate>
            <atom:updated>2021-03-10T21:40:19.418Z</atom:updated>
            <content:encoded><![CDATA[<p>It sometimes happens to me that my test don’t work as expected. And re-triggering the whole test just to figure out if some finder works properly could be very time consuming. Not to mention the data handler function debugging in the flutter driver extension. It is even bigger pain.</p><p>Because today flutter for web is in trends I will show how to deal with flutter driver issues within it. But the same approach can be done for mobile app as well. Probably I will share it in some other article.</p><p>So, lets take an application from story (<a href="https://arturkorobeynyk.medium.com/flutter-testing-using-flutter-driver-part-1-5e4bf9e0c719">https://arturkorobeynyk.medium.com/flutter-testing-using-flutter-driver-part-1-5e4bf9e0c719</a>). Very basic application that contains few widgets with key property specified and also contains a data handler function for flutter driver extension. In order to add test capabilities to the standalone application just paste the enableFlutterDriverExtension(); in the very beginning of the main function of the main.dart file. You can take data handler function from the test_driver/helpers.dart but that is not required if you don’t plan to work with data handler.</p><p>We can launch that application in chrome using:</p><pre>flutter run -d chrome</pre><p>Now when you have your flutter application with flutter driver extension running in your browser you can send test commands to it right from the browser console.</p><p>In order to trigger a tap on a widget by value key for example you would call:</p><pre>$flutterDriver(&#39;{&quot;command&quot;: &quot;tap&quot;, &quot;finderType&quot;: &quot;ByValueKey&quot;, &quot;keyValueString&quot;: &quot;counter&quot;, &quot;keyValueType&quot;: &quot;String&quot;}&#39;)</pre><p>For entering text into the focused field you will use:</p><pre>$flutterDriver(&#39;{&quot;command&quot;: &quot;enter_text&quot;, &quot;text&quot;: &quot;BlaBla&quot;}&#39;)</pre><p>And for sending command to the data handler function you need to use:</p><pre>$flutterDriver(&#39;{&quot;command&quot;: &quot;request_data&quot;, &quot;message&quot;: &quot;increaseBy1000000&quot;}&#39;)</pre><p>So now we know how to deal with flutter driver extension in web app. And knowing that we can improve our business with $flutterDriver instance by creating a chrome extension that will throw those commands by single button click.</p><p>I have created one for myself and that allows me to interact with flutter application within my browser with grace and pleasure significantly boosting tests debugging. You can get it here <a href="https://github.com/arturk/flutter-driver-chrome-extension">https://github.com/arturk/flutter-driver-chrome-extension</a></p><p>Install it as described in the repo. Then start your flutter web application with flutter driver extension enabled, open browser console to see the output, open the installed extension and try to do a few clicks, text entries and maybe data handler function calls (like those described in part 1 tutorial).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxnLsKytdLFdCFdQOdGhEQ.png" /></figure><p>By default extension works with raw payload. But if you chose json then you will need to parse it on the receiving side as well within the data handler function of the flutter driver extension.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6045785b15b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter testing using flutter driver, part 1]]></title>
            <link>https://arturkorobeynyk.medium.com/flutter-testing-using-flutter-driver-part-1-5e4bf9e0c719?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4bf9e0c719</guid>
            <category><![CDATA[flutter-driver]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 22:01:25 GMT</pubDate>
            <atom:updated>2021-03-11T19:34:27.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter testing using flutter driver</h3><p>I am planning to share my experience about testing flutter apps using flutter driver. We will try to use all the capabilities of the flutter driver on a very basic app that is autogenerated as soon as you create new flutter project. Lets assume that you have flutter and vscode set up already.</p><p>So lets create a flutter project first and open it in vscode:</p><pre>flutter create testing_tutorial &amp;&amp; vscode testing_tutorial</pre><p>Now lets compile and run our project (you need to have virtual or physical device available for avd or simply build it for a web browser):</p><pre>cd testing_tutorial &amp;&amp; flutter run</pre><p>You will see a regular counter app. Click <strong>+</strong> button several times to see tha app works as expected.</p><p>Now lets prepare this app for testing with flutter driver. In VS Code open the <em>pubspec.yaml</em> file and add following to the dev_dependencies:</p><pre>dev_dependencies:<br>  flutter_driver:<br>    sdk: flutter<br>  test: any</pre><p>After that you will need to run:flutter pub get</p><p>This will fetch all the needed libraries for you project.</p><p>Now we need to prepare our app for testing with flutter driver. In VS Code create file in folder <em>test_driver/driver.dart</em> file with the content</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:testing_tutorial/main.dart&#39; as app;</pre><pre>void main() {<br>  enableFlutterDriverExtension();<br>  app.main();<br>}</pre><p>In the <em>test_driver </em>folder of the project lets create a file named <em>driver_test.dart</em>. And populate it with the next content:</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;<br>import &#39;package:test/test.dart&#39;;<br><br>void main() {<br>  group(&#39;Counter App&#39;, () {<br>    final buttonFinder = find.byValueKey(&#39;increment&#39;);<br>    final counterTextFinder = find.byValueKey(&#39;counter&#39;);<br>    FlutterDriver driver;<br><br>    setUpAll(() async {<br>      driver = await FlutterDriver.connect();<br>    });<br>    tearDownAll(() async =&gt; driver?.close());<br><br><br>    test(&#39;increments the counter&#39;, () async {<br>      await driver.tap(buttonFinder, timeout: Duration(seconds: 10));<br>      expect(await driver.getText(counterTextFinder), &quot;1&quot;);<br>    });<br>  });<br>}</pre><p>Because in the test above we tap and check our widgets using the byValueKey finders we need to add these keys to the app. Open the lib/main.dart file and edit two widgets like:</p><pre>Text(<br>  &#39;$_counter&#39;,<br>  <strong>key: Key(&#39;counter&#39;),</strong><br>  style: Theme.of(context).textTheme.headline4,<br>),</pre><pre>...</pre><pre>floatingActionButton: FloatingActionButton(<br>  onPressed: _incrementCounter,<br>  <strong>key: Key(&#39;increment&#39;),</strong><br>  tooltip: &#39;Increment&#39;,<br>  child: Icon(Icons.add),<br>),</pre><p>Now make sure that your virtual or physical device is running so flutter can install app there and run the testing command:</p><pre>flutter drive --target=test_driver/driver.dart</pre><p>This command will compile and run the test_driver/driver.dart app and then will trigger test with the same name as app file name, so in this case test_driver/driver_test.dart</p><p>The test should be passing. At this point you did a regular tutorial from a flutter integration testing documentation. But what if you need to test some widget properties within your integration test? For example you want to check that the <strong>+</strong> button icon is of type Icons.add The documentation does not tell you how to do that but it is possible using the data handler function for the flutter driver extension.</p><p>Create new file test_driver/helpers.dart:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_test/src/all_elements.dart&#39;;</pre><pre>List&lt;T&gt; findWidgets&lt;T extends Widget&gt;() =&gt;<br>    collectAllElementsFrom(WidgetsBinding.instance.renderViewElement,<br>            skipOffstage: false)<br>        .map((e) =&gt; e.widget)<br>        .whereType&lt;T&gt;()<br>        .toList();</pre><pre>Future&lt;String&gt; dataHandlerFunction(String payload) async {<br>  switch (payload) {<br>    case &quot;getButtonIcon&quot;:<br>      var addButton = findWidgets&lt;FloatingActionButton&gt;().first;<br>      return (addButton.child as Icon).icon.codePoint.toString();<br>    default:<br>      return null;<br>  }<br>}</pre><p>Here you created dataHandlerFunction which does whatever action you want with the application based on input.</p><p>Also pay attention to the findWidgets function. It is a bit difficult to understand but what it does is finds list of widgets of whatever type you feed to it. It is something I retrieved from the deepest parts of flutter source code :) but that is very handy in everyday life.</p><p>Now change your test_driver/driver.dart file to</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;helpers.dart&#39;;<br>import &#39;package:testing_tutorial/main.dart&#39; as app;</pre><pre>void main() {<br>  enableFlutterDriverExtension(handler: dataHandlerFunction);<br>  app.main();<br>}</pre><p>In such way you set your flutter driver extension handler function to the function defined by you. This data handler function exists within the app and has full access to app resources. If you find the Icons.add in <em>package:flutter/src/widgets/icon_data.dart</em> package you will see its codePoint value 0xe567</p><p>Lets now create a test to verify that our icon codePoint has that value. Edit your test_driver/driver_test.dart file by adding this test:</p><pre>test(&#39;check button icon&#39;, () async {<br>  var buttonIcon = await driver.requestData(&quot;getButtonIcon&quot;);<br>  expect(buttonIcon, equals(0xe567.toString()));<br>});</pre><p>If you run this test it will pass. You can change the expected value to see that it fails properly. So now you see that in such way you can get whatever information you want about any widget in your app no matter it is visible or not.</p><p>But that not all. We can affect our app in any way as well. For example, lets fast forward our counter to 1 000 000 . You need to add this case to data</p><pre>    case &quot;increaseBy1000000&quot;:<br>      var addButton = findWidgets&lt;FloatingActionButton&gt;().first;<br>      for (var i = 0; i &lt; 1000000; i++) addButton.onPressed();<br>      return null;</pre><p>And then you can add another test:</p><pre>    test(&#39;increments by 1000000&#39;, () async {<br>      await driver.requestData(&quot;increaseBy1000000&quot;);<br>      expect(await driver.getText(counterTextFinder), &quot;1000001&quot;);<br>    });</pre><p>Try to run it, it will be much faster then using driver.tap() one million times.</p><p>Also you can deal with custom widgets, data and properties in such way which will not be possible with basic flutter driver capabilities. So this is something for you to start. I will try to provide other interesting features for testing soon in the next part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4bf9e0c719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do widget properties testing in Flutter while you run E2E tests]]></title>
            <link>https://arturkorobeynyk.medium.com/how-to-do-widget-properties-testing-in-flutter-while-you-run-e2e-tests-6a775d47def9?source=rss-d1c2ea533ba6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a775d47def9</guid>
            <category><![CDATA[widget-testing]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Artur Korobeynyk]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 13:20:44 GMT</pubDate>
            <atom:updated>2021-02-12T20:30:26.341Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets take a very generic flutter test of the default flutter application from the basic tutorial (<a href="https://techwithsach.com/code-snippets/default-flutter-application-main-dart/">https://techwithsach.com/code-snippets/default-flutter-application-main-dart/</a>):</p><pre>import &#39;package:flutter_driver/flutter_driver.dart&#39;;<br>import &#39;package:test/test.dart&#39;;<br><br>void main() {<br>  group(&#39;Counter App&#39;, () {<br>    final counterTextFinder = find.byValueKey(&#39;counter&#39;);<br>    final buttonFinder = find.byValueKey(&#39;increment&#39;);<br><br>    FlutterDriver driver;<br><br>    setUpAll(() async {<br>      driver = await FlutterDriver.connect();<br>    });<br><br>    tearDownAll(() async {<br>      driver?.close();<br>    });<br><br>    test(&#39;starts at 0&#39;, () async {<br>      expect(await driver.getText(counterTextFinder), &quot;0&quot;);<br>    });<br><br>    test(&#39;increments the counter&#39;, () async {<br>      await driver.tap(buttonFinder);<br>      expect(await driver.getText(counterTextFinder), &quot;1&quot;);<br>    });<br>  });<br>}</pre><p>In order to run this test with our application we need to enable the flutter driver extension in it and that is how you probably do it already in your E2E tests:</p><pre>import &#39;package:flutter_driver/driver_extension.dart&#39;;<br>import &#39;package:my_app/main.dart&#39; as app;<br><br>void main() {<br>  enableFlutterDriverExtension();<br>  app.main();<br>}</pre><p>But now lets imagine that you need to test button background color or form background or text font. How would you do it within your flutter driver? Some may say it is impossible but if you know how to extend your flutter driver extension functionality you can easily do the widgets’ properties testing within your E2E test.</p><p>So lets see how can you extend the flutter driver functionality. If you use some data handler within your enableFlutterDriverExtension function you can extend it with custom commands that can be sent from tests to app in order to trigger some functionality within your app. Example:</p><pre>enableFlutterDriverExtension(handler: (payload) async {<br>  if(payload == &quot;myOwnCommand&quot;) {<br>    // TODO: I can do anything here<br>  }<br>});</pre><p>If we define a data handler separately for convenience it can return something back into the test:</p><pre>Future&lt;String&gt; dataHandler(String msg) async {<br>  switch (msg) {<br>    case &quot;myOwnCommand&quot;: {<br>      // TODO: I can do anything here<br>      return &quot;Result&quot;;<br>    }<br>    default:<br>      throw AssertionError(&quot;No such command&quot;);<br>  }<br>}</pre><pre>enableFlutterDriverExtension(handler: dataHandler);</pre><p>Now within your test you may call the requestData method of the FlutterDriver in order to send that command to the application and get something out of it:</p><pre>test(&#39;Check button color&#39;, () async {<br>  String result = await driver.requestData(&quot;myOwnCommand&quot;);<br>  // TODO: Place to verify button color<br>});</pre><p>Now lets get back to the application. We need to be able to find our button widget within it. Reverse-engineering the internals of flutter driver extension I found a function called collectAllElementsFrom. It is used by the flutter driver within its internal widget finders. We can reuse it and write a simple function that can return list of any requested type of widgets that we need.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:flutter_test/src/all_elements.dart&#39;;</pre><pre>List&lt;T&gt; findWidgets&lt;T extends Widget&gt;() =&gt;<br>  collectAllElementsFrom(<br>      WidgetsBinding.instance.renderViewElement,<br>      skipOffstage: false)<br>    .map((e) =&gt; e.widget)<br>    .whereType&lt;T&gt;()<br>    .toList();</pre><p>This function uses <em>flutter_test</em> package functionality <em>collectAllElementsFrom</em> and loops through the rendered elements in the elements tree returning the list of all related widgets that has specified type. Sounds hard but works like a charm. This coding style should be more familiar to developers with Java and C++ experience.</p><p>Pay attention to how this function looks like. It is bread and butter of this approach. You can use this function like <strong><em>List&lt;Text&gt; wdg = findWidgets();</em></strong> and function will return list of all Text widgets. You can use it then like <strong><em>List&lt;RichText&gt; wdg = findWidgets();</em></strong> and it will return list of RichText widgets without any changes in the function itself. Almost magic!</p><p>Now in our dataHandler function in order to search for any widget we may do following:</p><pre>case &quot;myOwnCommand&quot;: {<br>  List&lt;FloatingActionButton&gt; btns = findWidgets();<br>  FloatingActionButton btn = btns.first;<br>  return btn.backgroundColor.value.toString;<br>}</pre><p>Then in our test:</p><pre>test(&#39;Check button color&#39;, () async {<br>  String result = await driver.requestData(&quot;myOwnCommand&quot;);<br>  expect(EXPECTED_COLOR, int.parse(result));<br>});</pre><p>And as you can see here, flutter driver extension gives you possibility to verify ANY property of ANY widget and even interact with those.</p><p>You need to get the font of some text widget? No problem:</p><pre>case &quot;myOwnCommand2&quot;: {<br>  List&lt;Text&gt; txts = findWidgets();<br>  Text txt = txts.first;<br>  return txt.style.fontFamily;<br>}</pre><p>Now you just verify that value within your test and that is all. Does not seems so hard and impossible now, right?</p><p>Well awesome tool, in general )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a775d47def9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>