<?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 Valera Zakharov on Medium]]></title>
        <description><![CDATA[Stories by Valera Zakharov on Medium]]></description>
        <link>https://medium.com/@valera.zakharov?source=rss-30951c700ba1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ayzoVxZhuGEzsVK3UKNIhg.jpeg</url>
            <title>Stories by Valera Zakharov on Medium</title>
            <link>https://medium.com/@valera.zakharov?source=rss-30951c700ba1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:26:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valera.zakharov/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[Android UI Automation: Part 2, Making It Easy]]></title>
            <link>https://medium.com/several-people-are-coding/android-ui-automation-part-2-making-it-easy-57335c7379cc?source=rss-30951c700ba1------2</link>
            <guid isPermaLink="false">https://medium.com/p/57335c7379cc</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Valera Zakharov]]></dc:creator>
            <pubDate>Wed, 10 Jan 2018 18:59:46 GMT</pubDate>
            <atom:updated>2018-01-10T18:59:46.781Z</atom:updated>
            <content:encoded><![CDATA[<p><em>by </em><a href="https://twitter.com/kevin_lai14"><em>Kevin Lai</em></a><em> and </em><a href="https://twitter.com/valera_zakharov"><em>Valera Zakharov</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzLoOI9IQRCwnI6sA-NGCw.jpeg" /><figcaption><a href="https://pixabay.com/en/chamonix-cable-car-aiguille-du-midi-2351332">Photo</a> by <a href="https://pixabay.com/en/users/Simon-3/">Simon</a> licensed under <a href="https://pixabay.com/en/service/terms/#usage">Creative Commons CC0</a>.</figcaption></figure><p>In <a href="https://slack.engineering/android-ui-automation-part-1-building-trust-de3deb1c5995">Part 1</a> we introduced the targeted and hermetic UI test approach that helped Slack Android engineers write hundreds of stable UI tests. However, as our UI test suite expanded, we detected a problem. When asked how easy it was to write tests on a scale from 1 (terrible) to 4 (excellent), developers ranked it a 2.5 (a resounding “<em>meh</em>”). In fact, the only category that ranked worse was related to build times.</p><p>As one developer put it — <em>“Writing quality UI tests is still a difficult thing to do. It would be great to have some time put into building up a base to work from.” </em>What a great suggestion! In the following Test Week (a quarterly hackathon focused on improving test infrastructure), we set out to address this.</p><h3>Robots to the Rescue?</h3><p>As a starting point, we looked at existing solutions that could help us better structure and organize our test code. The <a href="https://academy.realm.io/posts/kau-jake-wharton-testing-robots/">robot pattern</a> — a layer of abstraction encapsulating user-facing functionality on the screen — was a good place to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8xJXnS-DtKAAP-A." /><figcaption>Diagram 1. UI Test Architecture with Robots</figcaption></figure><p>By separating out <strong>what</strong> the test does with the UI from <strong>how</strong> it interacts with the UI, robots reduce code duplication, make tests more readable, and take some friction out of authoring tests.</p><p>However, in the case of targeted and hermetic UI tests, robots only solve part of the problem. What about the other side of the View?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0hBoKk-cLSbt4gzF5s1rQ.png" /><figcaption>Diagram 2. UI Test Architecture with thinking Robots</figcaption></figure><p>We found that the other side of the view — dealing with setting up hermetic state — is where developers struggled the most.</p><p>We previously showed a couple lines of code demonstrating how we feed data to the test via a mock data provider. In practice, it’s rarely just a couple lines, but more like this (except a lot longer in the case of more complex screens):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9908eb580babc0304574fdaf0262d7/href">https://medium.com/media/0d9908eb580babc0304574fdaf0262d7/href</a></iframe><p>We have many more components that need to know about a user and a channel within our app, but this should help illustrate the complexity of our test setup. These components need some minimum state before a View will display properly and give us access to part of the app under test. Before a developer can add a test for their feature, they must swap in test doubles for <em>everything else</em> that’s powering that View — a time-consuming endeavor that often requires sifting through code that was written by others. What’s more, each developer would find themselves in a similar situation, causing potentially every member of the team to go through the same cumbersome test-writing process over and over again.</p><p>Our attempts to tuck repetitive setup away into a Base class only got us so far. Tests inheriting from BaseActivityTest needed to set up additional test data, leading to the proliferation of repetitive mocking throughout our codebase. And it turned out this was the most time-consuming part of creating a UI test, prompting us to look for a better way.</p><h3>Introducing PowerPack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UrfScQBfRkDJQLFe." /><figcaption>Diagram 3. UI Test Architecture with Setup</figcaption></figure><p>If we consider the data as part of our test — which we should if the test is going to be targeted and hermetic — the UI Test Architecture starts to look a lot more like Diagram 3. Before interacting with Robots, the test has to do some setup on the other end of the spectrum so that our View is “powered” accordingly. Naturally, this starts to look like a test sandwich of sorts, albeit a bit of an imbalanced one since we have both the Models and Tests providing “What” data we’re testing. However, when we take a step back and consider what a Test is actually doing in the setup phase, it’s essentially creating some test models and returning them from the Presenters/Components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_wRBHApS9ySJUgyz." /><figcaption>Diagram 4. PowerPack</figcaption></figure><p>We saw a great opportunity to improve the developer experience. If we look at the UI Test Architecture from a slightly different perspective, with the Test interacting with the Robots on one side of the View and providing the Models on the other side of the View, it made sense to swap in something for the “How” behind the View — similar to Robots in front. In Diagram 4., we introduce the <strong>PowerPack pattern</strong> to encapsulate the complexity of <em>powering</em> the View.</p><p>Part of the complexity comes from figuring out what needs to know about the test data that’s provided, so that the test author can simply think of models and not components. In the case of a User, we introduced a UsersPack that leverages AutoValue to provide a builder interface. By default, the UsersPack is provided with a set of Components that need to know about Users as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472416ddb5bdd9981af00b847061bfd0/href">https://medium.com/media/472416ddb5bdd9981af00b847061bfd0/href</a></iframe><p>And it exposes a pack() method that encapsulates all of the repetitive mocking for all of the Components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d47ef86e16e85f22220e84123372f3b/href">https://medium.com/media/2d47ef86e16e85f22220e84123372f3b/href</a></iframe><p>In comparison, the ChannelsPack has a lot more Components than we originally illustrated (shown below). As such, we’ll leave it up to your imagination on how much more involved its pack() method is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3818767f639af9539441d9895fcfd151/href">https://medium.com/media/3818767f639af9539441d9895fcfd151/href</a></iframe><p>A side benefit of these model-specific Packs is that they can be used by unit tests directly to mock a subset of Components, but their main benefit in UI tests comes from grouping them into an app-wide Pack, which is injected with mocked dependencies and provides them automatically in the model-specific builders. For us, this is a <strong>SlackPowerPack</strong>, which reduces the complexity in a test setup as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6057dbd4a457dedcbf74f95daf6e4e4/href">https://medium.com/media/c6057dbd4a457dedcbf74f95daf6e4e4/href</a></iframe><p>The end result is a lot more clear and concise. The test author approaches a test by thinking of the test data and not the Presenters/Components that need to be mocked out.</p><p>It’s worth noting that the complexity in setting up the Presenters/Components with the test data hasn’t been removed — it’s just been abstracted away as seen in the UsersPack.pack() example above. Still, the benefit is that a team of developers only has to take this cumbersome hit once and any changes to Presenter/Component APIs benefit from updates in a single Pack class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBMkstLaqbexWUgIE0uzAg.png" /><figcaption>Diagram 5. UI Test Architecture — Targeted, Hermetic and PowerPacked</figcaption></figure><p>Using the Robot and PowerPack patterns in conjunction, our UI Test Architecture ends up looking like a View sandwich in Diagram 5. The Test manipulates the layer immediately in front of and behind the View, giving us a very targeted and hermetic test where all the complexity in interacting with the View and setting up state is encapsulated and abstracted away. For the test author, just as the Robot pattern provides a fluent API for entering text, tapping buttons, etc., the PowerPack pattern does the same for initializing users, channels, messages, or whatever other test data the app is dependent upon.</p><p>With the PowerPack, we saw a significant improvement in the Ease of Testing category of the Developer Experience survey (a jump from 2.5 to 2.92). A friendly Slack developer wrote this — <em>“Ease of test writing: this has improved a lot. It would be nice to take the time to update some of our old tests to use PowerPack/our latest patterns.”</em> And if they stopped there, we would have packed up and gone home. But they also went on to say this — <em>“I would also love an easy way to set up a workspace.”</em></p><p>Which got us thinking…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/94/1*Pb4pz_mThrquO3LrnzyJlA.png" /></figure><h3>PowerPack++</h3><p>Many of the Slack UI tests need a test workspace with channels, users, messages, and other data. We could use the SlackPowerPack builder to set all that up, but what if the setup could be reduced to just one line?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cedada8f43fcb34e0c8ced02c5955e/href">https://medium.com/media/02cedada8f43fcb34e0c8ced02c5955e/href</a></iframe><p>To accomplish this, we extract the data used to initialize the SlackPowerPack into a json config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b279215220a85b702a3f11a6734b5292/href">https://medium.com/media/b279215220a85b702a3f11a6734b5292/href</a></iframe><p>From there, we can inflate the JSON into model objects and feed them to our PowerPack:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c6c83f0a1d04dfadb645cd4804682f/href">https://medium.com/media/50c6c83f0a1d04dfadb645cd4804682f/href</a></iframe><h3>Beyond PowerPack</h3><p>Having reduced test setup from a twisted mess of mockito invocations to one line, we got thinking about the next chapter in our testing story.</p><p>The JSON config …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*Wex2TJld5zz4A55m." /></figure><p>… is strangely reminiscent of the data we retrieve from the <a href="https://api.slack.com/methods/channels.history">Slack API</a>. What if, we could charge the PowerPack automatically?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsbBtB53XyKIz9Ckul95Uw.png" /><figcaption>Diagram 6. Charging the PowerPack from E2E tests.</figcaption></figure><p>We maintain a small set of end-to-end tests that communicate with a real backend (stay tuned for a blog post about this topic). Using a library like <a href="https://github.com/airbnb/okreplay">OkReplay</a>, we could capture network traffic from these tests. This API data can then be replayed directly in tests (a technique we use for performance testing, in order to preserve the fidelity of the application under test) or it could be used to auto-charge the SlackPowerPack. Sounds promising — we intend to explore this idea in the near future.</p><h3>Results</h3><p>With our developer-driven test approach, we’ve been able to build up a robust test suite that actually resembles a balanced pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*MeujoBbb-qOimrOq_-S-7w.png" /><figcaption>Diagram 7. Android Test Pyramid at Slack</figcaption></figure><p>Our unit and UI tests gate every merge to master, ensuring that a developer can merge code with confidence. Equally important, the process of testing exposes gnarly areas of our app and naturally guides us towards writing better, more modular code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_ZkWnlltEvCQHkcJY6YQw.png" /><figcaption>Diagram 8. Slack CEO Stewart Butterfield congratulating the Android team on having a balanced testing pyramid. <a href="https://twitter.com/far33d/status/921188637592526848">Source</a>.</figcaption></figure><p>There is still a lot of work to do: building PowerPack++, covering legacy parts of the codebase, continuing to fight flakiness, and taking infrastructure that executes and manages tests to the next level. We look forward to sharing our progress on these initiatives. Thanks for reading!</p><p><em>If this is the kind of work that appeals to you, join our </em><a href="https://slack.com/careers/883590/engineering-manager-mobile-developer-experience"><em>Mobile Developer Experience team</em></a><em>. And if, instead, you’d like the idea of authoring UI tests themselves, we are looking for test-friendly </em><a href="https://slack.com/careers/273739/android-engineer"><em>Android engineers</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57335c7379cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/several-people-are-coding/android-ui-automation-part-2-making-it-easy-57335c7379cc">Android UI Automation: Part 2, Making It Easy</a> was originally published in <a href="https://medium.com/several-people-are-coding">Several People Are Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android UI Automation: Part 1, Building Trust]]></title>
            <link>https://medium.com/several-people-are-coding/android-ui-automation-part-1-building-trust-de3deb1c5995?source=rss-30951c700ba1------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3deb1c5995</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Valera Zakharov]]></dc:creator>
            <pubDate>Thu, 04 Jan 2018 19:39:17 GMT</pubDate>
            <atom:updated>2018-01-04T19:39:17.052Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How we integrated UI testing into the Android developer workflow at Slack</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-31yNWgt4_GmxDruKg5Nhw.jpeg" /></figure><p>Developer-driven automated testing is vital to the ongoing health and quality of a codebase. It does, however, come with a noticeable cost. This is especially true of UI testing — an area often avoided by even the most test-friendly of developers. In this two-part blog post, we explore how the Slack Android team made authoring and maintaining UI tests part of the development cycle.</p><p>In Part 1, we place UI testing in context of the larger quality landscape and outline an approach that helps produce tests stable enough to run continuously.</p><h3>Why Developers Should Author UI Tests</h3><p>Let’s start with acknowledging the fact that many of us have been in the situation where a one-line bug fix required hours of struggle with an automated test. Why go through the effort if you can just merge the code and continue adding more features?</p><p>If you have ever refactored legacy code with no test coverage, you may remember the “I too like to live dangerously” feeling as you pulled the trigger to merge. A robust automated test suite (including UI tests) allows a you to move quickly with confidence, rather than feeling like you’re sitting at a high-stakes table in Vegas.</p><p>This effect is especially critical as your team grows and complexity rises. Unless you’re building a throwaway prototype, don’t make the mistake of deferring testing to a “better” time. There is no better time than now.</p><p>Further, authoring UI tests is a systematic way to exercise the code that you are about to unleash onto other developers and users. From the standpoint of code design, test-driven development is not as much a validation method as a design principle that forces you to break up your code into smaller modules — a natural forcing function for a cleaner, more maintainable codebase.</p><p>Ultimately, teams where developers are responsible for testing their own code gain a significant advantage that only grows with time.</p><h3>Gaining Traction with UI Testing</h3><p>While most developers agree that unit-testing their code is a good idea, the sentiment is not as positive about UI testing, which is often pushed to dedicated QA teams. A <a href="https://goo.gl/forms/iq4GFXdbjVpTPUg02">recent small-scale survey</a> distributed to the Android development community suggests that <strong>¾</strong> of respondents write some kind of tests when working on features that involve UI. Of these developers, <strong>all</strong> did some kind of unit testing, but <strong>37%</strong> did not add UI tests for the feature. Here are the top concerns that were cited by respondents when asked — “What prevented you from authoring UI tests?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kf-4rcU9XKVWlnP6PuyEfQ.png" /><figcaption>Top reasons for not authoring UI tests (from external developer survey)</figcaption></figure><p>We distributed the same survey to the Slack Android team and, to our relief, the results showed a different picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*NAoUcU2EJqbx3UGI." /><figcaption>Slack developers write UI tests</figcaption></figure><p>What compelled Slack’s Android engineers to write, not only unit tests, but also UI tests? Was it the vast amounts of time they gained from not having to read email? Was it the glory of solving impossible problems? Was it the threat to remove Coconut LaCroix from the fridge? Or, perhaps, we found a UI test strategy that works for us.</p><h3>Slack’s Approach to UI Testing on Android</h3><p>Our strategy comes down to reducing the need for UI testing, while keeping the remainder of UI tests stable by making them targeted and hermetic. Let’s dive into these in detail.</p><h4>Avoid over-testing the UI</h4><p>No post about testing is complete without the famous geometric shape of testing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*xALyllP3iw9w7VnKLQYauQ.png" /></figure><p>As you move up the pyramid, “larger” tests (i.e. ones that involved interactions between more components) become more difficult to author, maintain and execute. A developer should, therefore, prefer to get the majority of coverage from smaller unit tests, while supplementing the suite with a smaller set of integration and end-to-end tests.</p><p>The idea is simple, but in practice, it is complicated — the Android framework invites a developer to bundle business logic with UI interactions in the Activity/Fragment classes. Without adding additional layers to the architecture, you may end up with code that is only testable through UI and, following the path of least resistance, your testing may end up inverted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IZZL5EEoqzoQsxCI." /><figcaption>Source: <a href="https://twitter.com/cermak_cz/status/743719704406036480">https://twitter.com/cermak_cz/status/743719704406036480</a></figcaption></figure><p>Like every other problem in computer science, this can be solved with <a href="https://en.wikipedia.org/wiki/Indirection">another layer of indirection</a>. Is it worth introducing this layer for the sake of decoupling business logic from UI? We absolutely believe so. Of the many MV* (MVC, MVP, MVVM, MVI, MVWTF, …) patterns out there, we chose to go with a variant of MVP, with a bi-directional contract between the Presenter (pure business logic) and View (encapsulating simple UI interactions).</p><p>Which one should you go with? There are many takes on which pattern works best. The <a href="https://github.com/googlesamples/android-architecture">Google Samples Android Architecture</a> repository includes a collection of samples and is a great place to start looking into the subject. With the recent introduction of <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a>, the Android team is also providing guidance and framework support for more testable architectures. Find a pattern that best fits your code base and go with it.</p><p>At this point, an astute (and lazy!) developer might ask — if I can test all complex business logic through unit tests, do I even need UI tests at all? Our answer to that is a resounding yes because it helps you avoid this situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*s8O1U3xqqM2V2sOT." /><figcaption>Source: <a href="https://twitter.com/thepracticaldev/status/733908215021199360">https://twitter.com/thepracticaldev/status/733908215021199360</a></figcaption></figure><p>By validating whether the UI can be inflated on the actual Android OS and that business and UI layers are glued properly, UI tests fill the middle (integration) layer of the test pyramid. Lastly, you do not want to miss out on the opportunity to <a href="https://youtu.be/uHoB0KzQGRg?t=2051">watch UI tests execute in parallel</a>. A good rule of thumb is to have at least one test per screen that launches the activity and performs a few simple UI interactions/checks.</p><h4>Keeping UI Tests Stable</h4><p>Remember that one of the third most cited concerns from the Android developer survey above was: “Lack of trust in results”. Can UI tests actually be stable or will we have to live in continuous Christmas mode?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hq2oECmBbsXI0RCi." /></figure><p>In reality, most UI tests end up being unstable because developers forget to follow two best practices in testing: test only what you need to test and keep full control of test state.</p><h4>Targeted UI Tests</h4><p>Let’s look at an example. If your test is meant to validate functionality of the settings screen, it should not navigate through the login process, open the navigation drawer, press the overflow button, and only then start the actual test interactions related to settings. That would make the test more difficult to author, slower to execute, and more likely to fail in code paths that are unrelated to the functionality under test.</p><p>Instead, the test should launch the settings activity directly. On Android that’s easy to do by including this Junit4 rule in your test class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed66721e029abc521db1298e32f67471/href">https://medium.com/media/ed66721e029abc521db1298e32f67471/href</a></iframe><p>But there’s a catch — if you do this without setting up application state, you’ll likely see a login activity or some other setup screen instead of settings. In our project, we solve this by using a combination of <a href="http://square.github.io/dagger/">Dagger</a> (a popular dependency injection framework) and <a href="http://site.mockito.org/">Mockito</a> (a framework for easily creating test doubles).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fd9747417bbc02ca80c4cd4a27c798d/href">https://medium.com/media/2fd9747417bbc02ca80c4cd4a27c798d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f9029b4a37a330c9675e93631e400ec/href">https://medium.com/media/4f9029b4a37a330c9675e93631e400ec/href</a></iframe><p>Note: For legacy reasons, we are still on Dagger 1. If you’re starting from scratch, refer to this <a href="http://blog.sqisland.com/2015/04/dagger-2-espresso-2-mockito.html">sample with Dagger 2</a>.</p><p>Having the ability to swap in a test double for any object in the graph, we can now simulate a logged-in state by swapping out the component of our application that is responsible for signaling such state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ca10de40de814469ecfc348476bd9d9/href">https://medium.com/media/7ca10de40de814469ecfc348476bd9d9/href</a></iframe><p>This leads us to the next section where we further discuss state.</p><h4>Hermetic UI Tests</h4><p>In relation to testing, the word hermetic means that the test is fully isolated from non-deterministic state and interactions. The randomness can creep into the test through data, background operations and interactions with other applications.</p><p><strong>Data</strong></p><p>We are now able to launch our screen directly without navigating through the rest of the application, but will it even show up given the fact that we did not go through our normal setup flow? That’s a trick question — chances are, the application would simply crash because the data model required for inflating the UI is not there.</p><p>There are multiple ways in which test data can be provided to the UI under test:</p><ul><li><em>API:</em> Most applications communicate with a backend to retrieve data, so you can intercept and replay network traffic during test execution.</li><li><em>Persistent Storage:</em><strong> </strong>Data retrieved from the backend is often stored in local storage, such as an SQLite database. At this layer, you can copy the required database files from a real user session to the application directory to inject data for testing.</li><li><em>Higher Level of Abstraction:</em><strong> </strong>Many application architectures add a layer between local/backend storage and the business-logic components that use the data. During testing, you can swap in a test double for this intermediate layer and use its methods to provide data for the screen under test.</li></ul><p>Our recommendation for functional UI testing is to use the “Higher Level of Abstraction” method. We use a layer of classes called data providers, which retrieve data from local and backend sources and provide it in a user-friendly <a href="http://reactivex.io/documentation/observable.html">Rx Observable</a> to business logic components. This approach reduces the footprint of what’s being tested, thus making the test even more targeted. It also comes with an important side-benefit of reducing non-determinism caused by background operations used during data fetching, which we’ll talk about shortly.</p><p>In the case of the MVP pattern, a reasonable alternative would be to swap in a fake Presenter (an even higher level of abstraction). We believe this approach goes too far. It is true that the Presenter should already be unit-tested, but in a functional UI test, we want to cover the integration boundary between the View and the Presenter.</p><p><strong>Background Operations</strong></p><p>We’ve now launched a screen and injected an initial set of fake data to be displayed in the UI. This, in itself, is already a win — we can test that the Activity can successfully inflate its view hierarchy. But it is likely that you would want to go further and actually interact with the screen to test a few basic operations. This is where the UI testing story often becomes sad. The reason is multithreading — Android tests run on the instrumentation thread, while the UI is processed on the UI thread, leading to race conditions between test interactions and UI state. <a href="https://developer.android.com/training/testing/espresso/index.html">Espresso</a> helps by synchronizing all operations with the UI thread and taking care of a few basic background mechanisms like AsyncTasks. But most complex applications use <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html">Executors</a> or <a href="http://reactivex.io/documentation/scheduler.html">Rx</a> to schedule background work and Espresso does not handle synchronization with these out-of-the-box.</p><p>A common anti-pattern at this point is to sprinkle a test with sleep calls or some other forms of sleep-and-retry mechanisms. If we were to identify the most common source of flaky UI tests, this would be it. If you want developers to believe in UI testing, forget about sleep (in the tests, of course).</p><p>Thankfully, there are better ways. One approach would be to use Espresso’s <a href="https://developer.android.com/training/testing/espresso/idling-resource.html">IdlingResource</a> mechanism to synchronize background operations, but this route can be complex and <a href="https://github.com/square/RxIdler/issues/6">error prone</a>.</p><p>A simpler and more resilient approach is to get rid of asynchronous background work altogether. Remember those useful DataProviders that we replaced with test doubles to feed data into our app? We can replace the background work with instantly-returning operations that get processed on the instrumentation test thread:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a0c6d1e2946ffe44236dca70540c5ed/href">https://medium.com/media/1a0c6d1e2946ffe44236dca70540c5ed/href</a></iframe><p><strong>Other Applications</strong></p><p>One strength of the Android operating system is its ability to facilitate interactions between applications through intents. At the same time, this brings another source of non-determinism to testing. For example, a particular part of your application may send an intent to the photo-gallery app when it needs the user to pick an image. Testing this interaction presents two problems. First, instrumentation UI tests cannot interact with the UI of external processes (a security limitation of the OS). You could work around this by using <a href="https://developer.android.com/training/testing/ui-automator.html">UiAutomator</a>, but here’s the second, more fundamental problem — interacting with a dependency that you’re not fully in control of breaks the hermetic seal. Thankfully, these are exactly the problems that <a href="https://developer.android.com/training/testing/espresso/intents.html">espresso-intents</a>, a mockito-like framework for Android intents, was designed to solve. Here’s a sample:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa55cf457253113ed5a4c7501d63b855/href">https://medium.com/media/aa55cf457253113ed5a4c7501d63b855/href</a></iframe><p>Some developers go a step further and isolate the current activity under test from other activities within the application. With this approach, if your test triggers a transition to another activity, there is no need to set up the state for the destination UI. The astute (and not lazy!) developer may point out that this amounts to behavior verification (as opposed to the <a href="https://testing.googleblog.com/2013/03/testing-on-toilet-testing-state-vs.html">recommended state verification</a>). That is a good point. We leave it up the reader to weigh the benefits of this approach versus the drawbacks.</p><h3>Mission Accomplished?</h3><p>With the Targeted and Hermetic approach, our developer-authored UI tests were stable enough to run in CI. We addressed an important concern of trust and got developers to believe in the utility of UI testing. However, there was still a problem — developers did not enjoy the process because it was too cumbersome and time-consuming. In Part 2 of this post, we’ll discuss how we tackled the problem of making UI testing easy, and dare we say, enjoyable.</p><p><em>Interested in joining our test-friendly engineering team? Check out the open Android and Mobile Developer Experience positions </em><a href="https://slack.com/careers/location/all-locations/dept/engineering"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3deb1c5995" width="1" height="1" alt=""><hr><p><a href="https://medium.com/several-people-are-coding/android-ui-automation-part-1-building-trust-de3deb1c5995">Android UI Automation: Part 1, Building Trust</a> was originally published in <a href="https://medium.com/several-people-are-coding">Several People Are Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>