<?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 Alex Zhukovich on Medium]]></title>
        <description><![CDATA[Stories by Alex Zhukovich on Medium]]></description>
        <link>https://medium.com/@Alex_Zhukovich?source=rss-ed1ac4ed780a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pVh7ZJeJdIRGAYrHTm26LQ.jpeg</url>
            <title>Stories by Alex Zhukovich on Medium</title>
            <link>https://medium.com/@Alex_Zhukovich?source=rss-ed1ac4ed780a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Alex_Zhukovich/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[Espresso Test Recorder in 2020]]></title>
            <link>https://proandroiddev.com/espresso-test-recorder-in-2020-f8ab01366e6b?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8ab01366e6b</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 09:01:01 GMT</pubDate>
            <atom:updated>2020-01-29T09:01:01.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kF9BRUeMAwjHuUdg5bcsdA.png" /></figure><p>The “Espresso Test Recorder” was presented at Google I/O 16 together with Android Studio 2.2. It was great news for Android Developer and everyone who connected with the Android Development because we can now create UI tests in just a few clicks. However, even right now (January 2020) this tool is not so popular and we will try to understand why.</p><p>First of all, let’s try to create a test case for one of the scenarios for the Standard Login screen.</p><p>Let’s go back to the <a href="https://proandroiddev.com/android-ui-testing-frameworks-b0b52187ceb">previous article</a> when we discussed frameworks for Android UI testing and try to generate test case for similar scenario.</p><h3>Espresso Test Recorder in Practice</h3><p>Scenario:</p><ul><li>Open <strong>SignInActivity</strong></li><li>Enter the “<strong>test</strong>” string into the email input field (id: <em>R.id.email</em>)</li><li>Press the “<strong>Sign In</strong>” button (id: <em>R.id.signIn</em>)</li><li>“<strong>An email address should be valid</strong>” message should be displayed (string const: <em>R.string.error_email_should_be_valid</em>)</li></ul><p>Let’s visualize a login screen of the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwaFx53M-NQF5NzCxyVtZw.png" /></figure><p>First of all, we should open the Espresso Test Recorder. We can find the “Record Espresso Test” sub-menu item in the “Run” menu item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*SUDFjWreGE7LaoUHD1tjcA.png" /></figure><p>The developing application will open on the device or emulator as well as the Espresso Test Recorder window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*mVWqFFQbU9fop-9eeoIUTA.png" /></figure><p>The next step is to start interaction with the connected device or emulator. Let’s press the “LOGIN” button on device or emulator and you can see that the “Tap” action will be added to the “Espresso Test Recorder” window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*MJxFavnYijoyYB4-LsYWfw.png" /></figure><p>Let’s finish the test case and do the following steps:</p><ul><li>Tap on “Email address”</li><li>Enter the “test” text</li><li>Hide the keyboard</li><li>Tap on the “SIGN IN” button</li></ul><p>After that, the snackbar message will be displayed on the screen and we should press “Add Assertion” so that the screen of the device will be scanned and we will see the following screen of the “Espresso Test Recorder.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*6yJHWaW6iC368AUiOAvzjg.png" /></figure><p>However, we will have a situation in which only one test case will be added to the file. This case is easy as we don’t need to wait for data from the file, database, or server, and everything works well. However, when you need to wait for data from any data source, you will have problems because your test will fail without waiting for data. However, we can use <strong>sleep </strong>or <strong>wait </strong>from UiAutomator framework, but I cannot recommend them. An additional problem is that the test case starts from the main screen of the application when recording the test scenario. Before the recording starts of the test case, we can change the main screen of the application in the AndroidManifest.xml file.</p><p>Generated code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d37a130535d59c6c1b97b6844f17c949/href">https://medium.com/media/d37a130535d59c6c1b97b6844f17c949/href</a></iframe><p>However, we can create the same test case in Espresso:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b25bdb19bb952ea1f300683112370384/href">https://medium.com/media/b25bdb19bb952ea1f300683112370384/href</a></iframe><p>As you can see, the Espresso Test Recorder cannot replace manually created test cases. So, let’s analyze issues which this tool has right now:</p><ul><li>One file has one test case, meaning that you will need a lot of files to cover basic scenarios.</li><li>No waiting mechanism supported; if the application waits for data from any data source, the recorded test will fail or we should manually use <strong>sleep</strong> or <strong>wait</strong> function from UiAutoator viewer as quick solution. However, generated test will fail without any changes.</li><li>Generated test code very detailed; this makes this test slow because the test case verifies many states and properties of View; usually, these checks can be skipped for the test case.</li><li>The “Espresso Test Recorder” generates code which is very complicated to maintain in the future.</li></ul><p>While it cannot fully replace creating manual test cases, it can help at some point in a real project.</p><blockquote>I recommend to invest time in learning a test framework to create efficient and elegant test cases.</blockquote><h3>Espresso Test Recorder for developers and QAs</h3><p>As you can see, the Espresso Test Recorder generates not very readable code and very often these tests execute longer when compared to manually created test cases. However, this tool can be helpful for developers in some cases.</p><p>Let’s imagine that you don’t have UI test cases. Unfortunately, this is a widespread case (during presentations about UI automation, I often ask the question: “How many of you write Android UI tests?” and the amount is always around 15–20%).</p><p>So, you want to do refactoring and you don’t have a lot of UI tests. As a result, you can generate a few scenarios which can be broken after you finish refactoring. After refactoring you can be sure that the most important cases will be working well. However, the Espresso Test Recorder has many limitations and you cannot generate a test case for any case. We can use it for an error handling inside the application without waiting for data from data sources.</p><p>However, I recommend improve knowledge in test automation and creating efficient test cases which will work faster and are easy to maintain.</p><h3>Resources</h3><ul><li><a href="https://developer.android.com/training/testing/espresso">Espresso overview</a></li><li><a href="https://proandroiddev.com/android-ui-testing-frameworks-b0b52187ceb">Android UI Testing Frameworks</a></li><li><a href="https://alexzh.com/2018/12/10/efficient-testing-android-app-tools/">Efficient Testing Android app — Tools</a></li><li><a href="https://github.com/AlexZhukovich/MapNotes">“Map Notes” project — GitHub</a></li></ul><p>This article was originally posted <a href="http://alexzh.com/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8ab01366e6b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/espresso-test-recorder-in-2020-f8ab01366e6b">Espresso Test Recorder in 2020</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</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 Testing Frameworks]]></title>
            <link>https://proandroiddev.com/android-ui-testing-frameworks-b0b52187ceb?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b52187ceb</guid>
            <category><![CDATA[android-testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[espresso]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 18:46:01 GMT</pubDate>
            <atom:updated>2019-09-19T20:24:58.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2OdNB-yhOseRshneinyFw.png" /></figure><p>Testing is an essential part of the software development process and product release. Often, there is a situation when there are two mobile applications to test: iOS and Android versions.</p><p>Even here, we have different options:</p><ul><li>One application which is built for different platforms</li><li>Two separate apps which look similar</li><li>Two completely different applications</li></ul><p>Today I would like to concentrate only on UI testing, and we will analyze different solutions for UI testing Android application.</p><p>I want to make this article more descriptive, and, if you’d like, you can find a source code of similar test cases written in the same language, but using different frameworks.</p><p><strong>Test case:</strong></p><ul><li>Open SignInActivity</li><li>Enter the “test” string into email input field (id: <em>R.id.email</em>)</li><li>Press the “Sign In” button (id: <em>R.id.signIn</em>)</li><li>“An email address should be valid” message should be displayed (string const: <em>R.string.error_email_should_be_valid</em>)</li></ul><p>Let’s visualize a login screen of the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwaFx53M-NQF5NzCxyVtZw.png" /><figcaption>Test case for the MapNotes application</figcaption></figure><h3>Frameworks</h3><p>We have different types of frameworks:</p><ul><li>Native frameworks (in case of Android: Espresso and UiAutomator)</li><li>Cross-platform frameworks: (Appium, Calabash, etc.)</li></ul><p>When we have application for different platforms, we want to create test cases which work for all platforms, including Android and iOS. However, in practice, we might have a situation where the applications are entirely different. In this case, investing in cross-platform frameworks can be wasting your time because you will try to create generic API for two separate applications. As a result, you will have one framework, one codebase, and various steps for similar actions on different platforms. In addition to this, you should answer the following question: Who will write UI test cases? If the answer is developers, they often know native testing frameworks.</p><p>So, let’s try to analyze three of the most popular frameworks for UI testing. Android application:</p><ul><li>Appium (cross-platform)</li><li>Espresso (native)</li><li>UiAutomator (native)</li></ul><h3>Appium</h3><p><a href="http://appium.io/">Appium</a> is an open-source mobile testing framework which supports Android and iOS. It can test any type of mobile application: native, web or hybrid. This means that we can create tests which will work on different platforms. However, in practice for testing the iOS application under the hood, it uses the XCTest and UiAitomator framework to test the Android app. The Appium frameworks interact with application use Selenium Web Driver and Node.js.</p><p>Pros:</p><ul><li>Cross-language framework (you can create test cases in Java, C#, JavaScript, Python, Ruby)</li><li>Appium has a lot of similarities to Selenium Web Driver. A lot of developers and testers have experience with Selenium, and this means that they can start working with Appium faster</li><li>Executing test cases for different platforms from the same code base</li><li>Support for testing native, hybrid, and mobile-web applications</li></ul><p>Cons:</p><ul><li>Minimum Android SDK is 16</li><li>Test cases are slow</li><li>Test code stored separately from application code</li><li>Two sets of steps for the different platforms when apps are different from a UI perspective</li></ul><p>Note: <em>In case of Appium framework, we start from the main Activity of the application. That’s a SplashActivity which open LoginActivity when User is unauthorized.</em></p><p>Test case implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7dac6e3fa4af0b634e754a452acac7/href">https://medium.com/media/2b7dac6e3fa4af0b634e754a452acac7/href</a></iframe><p>Average execution time of the test scenario: <strong>12 sec 15 ms</strong></p><h3>Espresso</h3><p><a href="https://developer.android.com/training/testing/espresso">Espresso</a> is Google’s framework for UI testing, which has a simple API and allows us to write readable UI test cases. The Espresso framework has a dependency on the Hamcrest library and supports Matchers from it, which simplifies testing complicated scenarios by introducing custom matchers and actions.</p><p>Espresso has a few additional modules:</p><ul><li><strong>espresso-web</strong> (Contains resources for WebView support)</li><li><strong>espresso-idling-resource</strong> (Espresso’s mechanism for synchronization with background jobs)</li><li><strong>espresso-contrib</strong> (External contributions that contain DatePicker, RecyclerView and Drawer actions, accessibility checks, and CountingIdlingResource)</li><li><strong>espresso-intents</strong> (Extension to validate and stub intents for hermetic testing)</li><li><strong>espresso-remote</strong> (Location of Espresso’s multi-process functionality)</li></ul><p>Pros:</p><ul><li>Fast execution time of test cases</li><li>Espresso support synchronization, which means you don’t need to write additional code for waiting until activity/fragment will be loaded or finished</li><li>Espresso support testing components in isolation. You can execute test cases for any activity or fragment</li><li>Supporting Hamcrest Matchers, which might be familiar to developers</li><li>Can test Web components</li></ul><p>Cons:</p><ul><li>Test cases can be created only for the Android platform</li><li>Test cases can be written exclusively in Java/Kotlin</li><li>The application should be ready for writing efficient tests with Espresso (proper animation handling which allows you to disable all animations because it a requirement for using Espresso framework)</li></ul><p>Note: <em>In case of Espresso framework, we might start from any Activity from the Application.</em></p><p>Test case implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b25bdb19bb952ea1f300683112370384/href">https://medium.com/media/b25bdb19bb952ea1f300683112370384/href</a></iframe><p>Average execution time of the test scenario: <strong>0 sec 967 ms</strong></p><h3>UiAutomator</h3><p><a href="https://developer.android.com/training/testing/ui-automator">UiAutomator</a> is Google’s UI testing framework, which allows us to test any application installed on the device.</p><p>In addition to it, we can interact with system components (Runtime Permission Dialog, Notifications, etc.) and interact with hardware buttons.</p><p>UiAutomator is delivered with a UiAutomatorViewer. This tool helps you to explore the UI of any application. I recommend <a href="https://alexzh.com/2018/12/10/efficient-testing-android-app-tools/">to check out the article “Efficient Testing Android app — Tools”</a> which describes available Android tools for analyzing UI.</p><p>Pros:</p><ul><li>Interaction with system components</li><li>Simple API of the framework</li></ul><p>Cons:</p><ul><li>Minimum Android SDK is 18 (Android 4.3)</li><li>Complicated API for working with lists</li><li>No support for working with web elements</li></ul><p>Note: <em>In case of UiAutomator framework, we start from the main Activity of the application. That’s a SplashActivity which open LoginActivity when User is unauthorized.</em></p><p>Test case implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d9e41ff630659ba79688788cf81a566/href">https://medium.com/media/7d9e41ff630659ba79688788cf81a566/href</a></iframe><p>Average execution time of the test scenario: <strong>8 sec 743 ms</strong></p><h3>UiAutomator &amp; Espresso</h3><p>Take a look at Espresso and UiAutomator frameworks in isolation; it’s not very honest, because we can create test cases where we can use Espresso and UiAutomator frameworks together. It gives us benefits from both frameworks. I recommend <a href="https://alexzh.com/2016/08/21/android-testing-espresso-uiautomator-together/">to check out the “Android testing: Espresso &amp; UIAutomator together” article</a>.</p><h3>Summary</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6d34b54164015c443772f969b910ee/href">https://medium.com/media/0c6d34b54164015c443772f969b910ee/href</a></iframe><h3>Resources</h3><ul><li><a href="http://appium.io/">Appium official website</a></li><li><a href="https://developer.android.com/training/testing/espresso">Espresso overview</a></li><li><a href="https://developer.android.com/training/testing/ui-automator">UiAutomator overview</a></li><li><a href="https://alexzh.com/2018/12/10/efficient-testing-android-app-tools/">Efficient Testing Android app — Tools</a></li><li><a href="https://alexzh.com/2016/08/21/android-testing-espresso-uiautomator-together/">Android testing: Espresso &amp; UIAutomator together</a></li></ul><p>This article was originally posted <a href="http://alexzh.com/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b52187ceb" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-ui-testing-frameworks-b0b52187ceb">Android UI Testing Frameworks</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android ProcessLifecycleOwner by example]]></title>
            <link>https://proandroiddev.com/android-processlifecycleowner-by-example-2f965061b9da?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f965061b9da</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 04:47:03 GMT</pubDate>
            <atom:updated>2023-06-03T21:40:33.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqOO1xvyFDOvJJ5Z_DGnag.png" /></figure><blockquote>This article was updated on 2 July 2023. The original article was published on 19 August 2019.</blockquote><p>Nowadays, users have many installed applications. It means that users often interact with many applications during a short amount of time. For example, when the user interacts with an application, receives a notification, then goes to another app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueLMYoU8vJkAQxiOXj8t_w.png" /><figcaption>Different states of the application</figcaption></figure><p>However, as being developers, we would like to know when our application moved to the background. It’s a very popular use case for analytics. Different analytics solutions define sessions in different ways, some solutions allow developers to define “session” meaning. Let’s create a simple analytics abstraction which informs us about the duration of the session, which will be calculated in the following way: when we start the application, the session is also started and when the application moves to the background, our session is finished. Finally, we would like to display this information in logs.</p><p>The ProcessLifecycleOwner can help us get information about changing the state of the application.</p><p>So, let’s start with adding dependencies for lifecycle framework:</p><pre>dependencies {<br>    ...<br>   <br>    implementation &#39;androidx.lifecycle:lifecycle-process:2.6.1&#39;<br>}</pre><p>Let’s start with creating an ApplicationObserver class which helps us to handle the changing state of the application and configure our analytics solution in a proper way. So we want to know when our application moved to the background and to the foreground. We can use lifecycle event for it:</p><ul><li>when application moved to background ON_STOP event will be triggered;</li><li>when application moved to foreground ON_START event will be triggered.</li></ul><p>We can create an ApplicationObserver class which simplifies defining sessions for the analytics.</p><pre>class ApplicationObserver(val analytics: Analytics) : DefaultLifecycleObserver {<br>    <br>    override fun onStart(owner: LifecycleOwner) {<br>				<br>    }<br><br>    override fun onStop(owner: LifecycleOwner) {<br>        <br>    }<br>}</pre><p>The next step is attaching the ApplicationObserver to our application. We should register this observer in the application class. In my case, it&#39;s a MapNotesApp class. So, we should register it inside <em>onCreate</em> method. We can use the following code for initialization of ProcessLifecycleOwner and registering ApplicationObserver component.</p><pre>class MapNotesApp : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        ...<br><br>        val analytics = Analytics()<br>        analytics.addReporter(LogReporter())<br><br>        ProcessLifecycleOwner<br>            .get()<br>            .lifecycle<br>            .addObserver(ApplicationObserver(analytics))<br>    }<br>    ...<br>}</pre><p>At the moment we can move to creating an abstraction for the analytics. I suggest to create a simple solution which can be extended, but even this implementation will be enough for demo purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BN8eIhm16m4OZaMqqpbFEg.png" /></figure><p>The Analytics class allows us to collect session information.</p><pre>class Analytics {<br>    private var startSessionTimestamp: Long = -1<br>    private val reporters = mutableListOf&lt;AnalyticsReporter&gt;()<br><br>    fun addReporter(reporter: AnalyticsReporter) {<br>        reporters.add(reporter)<br>    }<br><br>    fun startSession() {<br>        startSessionTimestamp = Date().time<br>    }<br><br>    fun stopSession() {<br>        reportSession()<br>        sendAllEvents()<br>        startSessionTimestamp = -1<br>    }<br><br>    private fun reportSession() {<br>        reporters.forEach {reporter -&gt;<br>        val currentTime = Date().time<br>        // we should check if session was started and stopped correctly<br>        val sessionTime = (currentTime - startSessionTimestamp) / 1000<br>            reporter.report(&quot;Session time: $sessionTime sec&quot; )<br>        }<br>    }<br><br>    private fun sendAllEvents() {<br>        reporters.forEach {reporter -&gt;<br>            reporter.sendAllEvents()<br>        }<br>    }<br>}</pre><p>The AnalyticsReporter interface is an abstraction for all reporters, like <em>LogReporter</em>.</p><pre>interface AnalyticsReporter {<br><br>    fun report(event: String)<br><br>    fun sendAllEvents()<br>}</pre><p>The LogReposter is implementation for the AnalyticsReporter interface. It displays all logs in the console.</p><pre>class LogReporter : AnalyticsReporter {<br>    private val events = mutableListOf&lt;String&gt;()</pre><pre>    override fun report(event: String) {<br>        events.add(event)<br>    }</pre><pre>    override fun sendAllEvents() {<br>        events.forEach { event -&gt;<br>            Log.d(this.javaClass.simpleName, event)<br>        }<br>        events.clear()<br>    }<br>}</pre><p>The LogReposter is implementation for the AnalyticsReporter interface. It displays all logs in the console.</p><pre>class LogReporter : AnalyticsReporter {<br>    private val events = mutableListOf&lt;String&gt;()<br><br>    override fun report(event: String) {<br>        events.add(event)<br>    }<br><br>    override fun sendAllEvents() {<br>        events.forEach { event -&gt;<br>            Log.d(this.javaClass.simpleName, event)<br>        }<br>        events.clear()<br>    }<br>}</pre><p>Finally, we can update the ApplicationObserver class for starting and stopping the session.</p><pre>class ApplicationObserver(val analytics: Analytics) : DefaultLifecycleObserver {<br><br>    override fun onStart(owner: LifecycleOwner) {<br>        super.onStart(owner)<br>        analytics.startSession()<br>    }<br><br>    override fun onStop(owner: LifecycleOwner) {<br>        super.onStop(owner)<br>        analytics.stopSession()<br>    }<br>}</pre><p>Afterwards, we can run our application and check the log. When the application moves to the foreground, our session starts, but when the application moves to the background, we finish our session with small delay and display this information in logs.</p><pre>com.alex.mapnotes D/LogAnalyticsReporter: Session time: 28 sec</pre><p>The main reason for this delay is the internal implementation of ProcessLifecycleOwner and we will talk about it in a moment.</p><p>So, let’s move between different screens because the duration of our session is independent on the current activity. As you can see, we can easily handle case when the application moves from foreground and background and vice versa. Analytics it just one of the example when we need this information.</p><p>Let’s check how ProcessLifecycleOwner works under the hood. Everything starts when we add the <em>&quot;lifecycle-process&quot;</em> dependency to the project. After building it, the ProcessLifecycleInitializer will be added to <em>AndroidManifest.xml</em> as a provider which allows the framework to collect the information about changing states of the activities. The main helper here is <strong>ReportFragment</strong>, which sends information about changes in the lifecycle of each activity to LifecycleRegistry class. That is a hub for collecting information about the lifecycle and it can notify an interested observer about changes in the lifecycle of <strong>LifecycleOwners</strong>. However, the framework has one trick that is a delay and it is used for verification that no new activity was created, and this delay is equal to <strong>700</strong> milliseconds.</p><p>An implementation can be found at <a href="https://gist.github.com/AlexZhukovich/9d4047a1b0dbd8280545d86703380697">Github</a> and it was originally posted <a href="http://alexzh.com/">here</a>.</p><p>If you have any questions please reach out on Twitter or leave a comment.</p><p><a href="https://twitter.com/Alex_Zhukovich">Alex Zhukovich</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f965061b9da" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-processlifecycleowner-by-example-2f965061b9da">Android ProcessLifecycleOwner by example</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing code between local and instrumentation tests]]></title>
            <link>https://proandroiddev.com/sharing-code-between-local-and-instrumentation-tests-c0b57ebd3200?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0b57ebd3200</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 07:09:55 GMT</pubDate>
            <atom:updated>2019-02-02T13:07:25.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hCJvMW6E3kz6M5XwcCKWA.jpeg" /></figure><p>I would like to talk about sharing code between local and instrumentation test cases. We often use almost similar test data for them. It can be a factory which produces test data for us or predefined set of data. We usually split local and instrumentation test cases into different folders; it means that we should duplicate test data or factories for generating test data.</p><p>Alternatively, we can create a common test folder where we can store files, classes, functions which will be available for local and instrumentation tests.</p><p>Recently was announced that we can run <a href="https://developer.android.com/training/testing/espresso/">Espresso</a> tests with a <a href="http://robolectric.org/">Robolectric </a>framework. However, we would like to avoid code duplication if we want to have a possibility of running the same tests cases as local and instrumentation tests. We have different folders for local and instrumentation tests, and we can create a shared folder for test cases which can be run as local or instrumentation tests.</p><p>Sharing code allows us to reduce code duplication for test data and test cases.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1yvFyysxXiI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1yvFyysxXiI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1yvFyysxXiI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae3bd25dd4a14a29e2e94b51d697b235/href">https://medium.com/media/ae3bd25dd4a14a29e2e94b51d697b235/href</a></iframe><h3>Sharing test data between local and instrumentation test cases</h3><p>Let’s take a look at different test cases which use the same data. I want to show you test cases from MapNotes app. The source code of the app you can find on <a href="https://github.com/AlexZhukovich/MapNotes">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVuBIhfGfSF-mYGGHEuDlQ.png" /><figcaption>MapNotes application</figcaption></figure><p>We can start with local unit test cases, which verify different that <em>SignInPresenter</em> works correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd96f080bc8a0d7bb9af330f4a98566/href">https://medium.com/media/0cd96f080bc8a0d7bb9af330f4a98566/href</a></iframe><p>As you can see, we use prepared earlier data for verification sign in process. In this case, we use<strong> <em>CORRECT_EMAIL</em></strong>,<em> </em><strong><em>PASSWORD </em></strong>and <strong><em>AUTH_USER</em></strong><em> </em>constants. The same set of test data we can use for verification <em>SignIn </em>screen with UI instrumentation test case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b424ca326fee0237a4da6bbb3f8b190b/href">https://medium.com/media/b424ca326fee0237a4da6bbb3f8b190b/href</a></iframe><p>The main problem here is that we store the same data twice for local and instrumentation test cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bux1YneZcgewkPFYbxdhtA.jpeg" /></figure><p>As you can see, we have two almost similar files because they can have an additional set of data which is used only for some category of tests (local or instrumentation).</p><p>We can avoid file duplication with creating a shared folder for local and instrumentation test cases and store test data in this directory because after it we will have access to this data from both categories of tests.</p><p>First of all, we should go to the <strong>Project Structure</strong> view and change it to Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*kBxKgBSug8kY1svNs4XSjg.jpeg" /></figure><p>After it, we can have the same structure, as we have on a disk, which helps us to configure a shared folder and see it at the beginning in Android Studio.</p><p>Afterwards, we should create a new folder; I prefer to call it “sharedTest“. However, everything depends on the purposes of the folder.I’ll create a “sharedTest” folder where I want to store test data and test cases for similar scenarios for local and instrumentation tests. The next step is to create a “java” folder if you use the default structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*js-C0erlX2U0Iz0H2F17OA.jpeg" /></figure><p>When it’s done, we can create a package where we want to store our test data, in my case, it’s a <em>com.alexzh.mapnotes</em> package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*ONZCd36aawNe2lv24DQRcQ.jpeg" /></figure><p>Finally, we can move to the build.gradle. We should open this file and add a <strong>sourceSets</strong> section to <strong>android</strong> one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa06dcfb6cb85d37fe3e74c253e4cfe9/href">https://medium.com/media/fa06dcfb6cb85d37fe3e74c253e4cfe9/href</a></iframe><p>After moving files to the shared folder and removing them from <em>test</em> and <em>androidTest</em> folders, we avoid duplication and all test cases work correctly.</p><p>Another approach is using factories which will generate test data for us, like TestDataFactory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538568ddc131099c58736cb1ed8931f4/href">https://medium.com/media/538568ddc131099c58736cb1ed8931f4/href</a></iframe><h3>Sharing test code and running the same scenarios with local and instrumentation tests</h3><p>Let’s start with checking dependencies which project should have for Espresso, Robolectric, Runners and extensions. I grouped all dependencies for better reading, and everything works fine with these versions of dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f852e14c37442ce4ca329d4a84ed6bfd/href">https://medium.com/media/f852e14c37442ce4ca329d4a84ed6bfd/href</a></iframe><p>Afterwards, we should move the <em>LoginActivityTest</em> test class to <strong>sharedTest</strong> folder. After it, we will have a problem with dependencies because we are using the few modules for dependency injection. It means that we should move <em>TestAppModule</em> file with all dependencies and <em>FakeMapFragment</em> as one of the dependencies which should be available for <em>TestAppModule</em>. Finally, we can run our tests without any modification. Let’s check these tests with local and instrumentation tests and see the time difference between them.</p><p>Finally, we can create configurations for running <em>LoginActivityTest </em>as local and as instrumentation tests or use gradle tasks.</p><p><strong>Running a specific test class as instrumentation tests use gradle:</strong></p><pre>./gradlew :MODULE:connectedVARIANTAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=PACKAGE.CLASS</pre><p>Example:</p><pre>./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.alex.mapnotes.login.LoginActivityTest</pre><p><strong>Running a specific test class as local tests use gradle:</strong></p><pre>./gradlew :MODULE:testVARIANTUnitTest --tests &quot;PACKAGE.CLASS&quot;</pre><p>Example</p><pre>./gradlew :app:testDebugUnitTest --tests &quot;com.alex.mapnotes.login.LoginActivityTest&quot;</pre><p>I had the next results:</p><ul><li>Instrumentation tests: <strong>10s 792ms</strong></li><li>Local test: <strong>4s 669ms</strong></li></ul><p>To sum up, sharing code between different categories of tests helps you to reduce code duplication for test data and test in general when we use the same test cases for local and instrumentation when we want to run tests with Robolectric and Espresso.</p><p>This article was originally posted <a href="http://alexzh.com/">here</a>.</p><p>If you have any questions please reach out on Twitter or leave a comment.</p><p><a href="https://twitter.com/Alex_Zhukovich">Alex Zhukovich</a></p><p>More video tutorials:</p><p><a href="https://www.youtube.com/channel/UCGaWGZ23II5am251vQCEt_Q">AlexZh Dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0b57ebd3200" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/sharing-code-between-local-and-instrumentation-tests-c0b57ebd3200">Sharing code between local and instrumentation tests</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Android Notifications]]></title>
            <link>https://proandroiddev.com/testing-android-notifications-f147a572b257?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f147a572b257</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 21:51:53 GMT</pubDate>
            <atom:updated>2019-09-15T19:19:11.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*473YJXqmC21LfsdEHrmQhA.png" /></figure><h3>Introduction</h3><p>Testing allows us to improve the quality of the product because after any changes you can be sure that all your basic functionality works correctly.</p><p>We can test different parts of our application, and one of these parts are notifications (almost all application use them for different purposes). Recently, I wrote, <a href="http://alexzh.com/tutorials/notification-for-android/"><strong>“Guide: Android notifications”</strong></a> and if you are not familiar with this topic, I recommend to read it, because it allows you to improve knowledge about this topic.</p><p>The <a href="https://github.com/AlexZhukovich/NotificationDemo"><strong>NotificationDemo</strong></a> repository contains demo application for Android notifications and UI tests from the project. Additionally, the <a href="https://github.com/AlexZhukovich/NotificationDemo/pull/2"><strong>PR: “Adding UI tests”</strong></a> shows all changes for adding the UI tests and Kotlin to the project.</p><h3>Specific of Android testing</h3><p>Before testing Android application, we should discuss few specific aspects for this platform.</p><ul><li>We have two different types of tests: local and instrumentation.</li><li>The local tests are run on local JVM, it means that we can run these tests on our development machine or CI (Continuous Integration) without additional devices.</li><li>The instrumentation test cases are run on a device or an emulator. If we want to use CI (Continuous Integration), we should connect additional devices for these tests or run the emulator.</li><li>Local tests are much faster than instrumentation ones. As a result, we should have much more local tests which can verify business logic of the product, for efficient testing.</li><li>Instrumentation tests can be splitted to UI and non-UI instrumentation test cases.</li><li>Non-UI instrumentation tests are much faster than UI ones because we don’t need to wait for loading Activities, Fragments and View. In addition to it, UI tests usually wait for loading data from any data sources.</li></ul><h3>Problems of testing notifications</h3><p>Coming back to the notifications, we should verify many different scenarios:</p><ul><li>displaying a notification</li><li>interacting with notification by tapping to notification and actions</li><li>interacting with bundle notification</li><li>supporting notification badges</li></ul><p>Some of these scenarios cannot be important for some applications. Another one can provide system features, like <em>“Notification Badge”</em>, but if it’s important to you, it can be tested. I mean that when some of the developers change channel setting and turn off the supporting of notification badge, the test can fail and it will be an indication for you.</p><p>I would like to show you testing all scenarios. However, some of them can be optional for your product.</p><h3>Frameworks and tools for UI testing in Android</h3><p>Let us explore tools which we can use for creating UI test cases for notification verification. We can use different frameworks for testing Android applications:</p><ul><li><a href="https://developer.android.com/training/testing/espresso/"><strong>Espresso</strong></a> is a framework for emulating user behaviour within an application.</li><li><a href="https://developer.android.com/training/testing/ui-automator"><strong>UiAutomator</strong></a> framework allows us to interact with a system, different applications, notifications, hardware buttons, etc.</li><li><a href="http://appium.io/"><strong>Appium</strong></a> is an open source test automation framework for using with native, hybrid and mobile web apps.</li><li>etc.</li></ul><p>We will discuss how to test notifications with Espresso and UiAutomator frameworks and I will also tell you about basic possibilities of these frameworks.</p><h3>Espresso</h3><p>Espresso is a framework for emulating user behaviour within an application. We can interact with different widgets: Buttons, CheckBox, EditText, RecyclerView, etc. One of the most significant benefits of this framework is writing tests without sleep, because Espresso has Idling Resource mechanism, which allows us to do actions and verifications of different components from different activities without any problem and workarounds, like sleep.</p><p>If you not familiar with Espresso I can recommend you few resources:</p><ul><li><a href="https://developer.android.com/training/testing/espresso/"><strong>Official webpage</strong></a></li><li><a href="http://alexzh.com/tutorials/android-testing-espresso-part-3/"><strong>Tutorial</strong></a></li></ul><h3>UiAutomator</h3><p>UiAutomator framework allows us to interact with a system, different applications, notifications, hardware buttons, etc.</p><p>If you are not familiar with UiAutomator, I can recommend you few resources:</p><ul><li><a href="https://developer.android.com/training/testing/ui-automator#ui-automator-viewer"><strong>Official webpage</strong></a></li><li><a href="http://alexzh.com/tutorials/android-testing-ui-automator-part-4/"><strong>Tutorial</strong></a></li></ul><h3>UiAutomatorViewer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WrMQeRxxnk8tGwuejjTFw.png" /><figcaption>UiAutomatorViewer demo</figcaption></figure><p>UiAutomatorViewer is a tool which provides information about any view on the screen; it means that we can explore IDs of different applications, like Launcher. It allows you to create test cases with UiAutomator which interacts with any application. In this way, we can test the <em>“notification badge”</em> feature, open links from any application via your browser (if you created browser).</p><p>You can run this UiAutomatorViewer from the <strong>{android-sdk}\tools\bin</strong> folder.</p><blockquote>We can combine Espresso and UiAutomator frameworks even in a single test and create efficient and powerful test cases.</blockquote><h3>Practice: Testing notifications</h3><p>Let us explore how we can add tests for notifications verification. We have many cases for checking of any notifications:</p><ul><li>displaying essential information</li><li>tapping on the notification</li><li>tapping on the action</li><li>interacting with notification bundle</li><li>interacting with notification badge</li></ul><p>Surely, you can have other cases, but I am trying to show you the general use cases.</p><p>First of all, I recommend to create additional methods which can help us with testing notifications.</p><p>The clearAllNotifications method is needed for clearing all notifications in notification ares. We archiving it with <em>“CLEAR ALL”</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw1lyHHjw5dd1W3yWQGAOA.png" /><figcaption>Clear all button in notification area</figcaption></figure><pre>private fun clearAllNotifications() {<br>    val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())<br>    uiDevice.openNotification()<br>    uiDevice.wait(Until.hasObject(By.textStartsWith(expectedAppName)), timeout)<br>    val clearAll: UiObject2 = uiDevice.findObject(By.res(clearAllNotificationRes))<br>    clearAll.click()<br>}</pre><p>In this case, we use UiAutomator framework which allows us to interact with Android OS. This method opens notification area, waits for notification (because this framework hasn’t got smart waiting mechanism, like IdlingResources in Espresso). Afterwards, we are looking for the <em>“CLEAR ALL”</em> button and click on it.</p><p>The clickOnSendNotification ViewAction is needed for tapping to the view with <em>send_button</em> ID for one of items in the RecyclerView.</p><pre>private fun clickOnSendNotification() : ViewAction {<br>    return object : ViewAction {<br>        override fun getDescription(): String {<br>            return &quot;Click on the send notification button&quot;<br>        }<br><br>        override fun getConstraints(): Matcher&lt;View&gt; {<br>            return Matchers.allOf(isDisplayed(), isAssignableFrom(Button::class.java))<br>        }<br><br>        override fun perform(uiController: UiController?, view: View?) {<br>            view?.findViewById&lt;View&gt;(R.id.send_button)?.performClick()<br>        }<br>    }<br>}</pre><p>Here we verify that a button with the send_button is displayed and we click on it.</p><p>The last interesting moment of testing notification is floating-notification. You can see this situation when notification is displayed and overlaps part of an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Be6VIhmSQrjpOooxTHNXEg.png" /><figcaption>Floating notification</figcaption></figure><p>We can disable it using the <strong>adb command</strong> for a device or an emulator</p><blockquote>adb shell settings put global heads_up_notifications_enabled 0</blockquote><p>However, if we want to have floating notification feature enabled ,we can add swipe to notification for hiding current notification. Sorry for this code — I am ashamed of this workaround, but sometimes it can be helpful. However, I strongly recommend to turn of the floating-notification feature for testing purposes.</p><pre>/**<br> * Workaround for swiping down the floating notification.<br> * As an alternative, we can turn off them using the<br> * &lt;pre&gt;<br> * {@code adb shell settings put global heads_up_notifications_enabled 0}<br> * &lt;/pre&gt;<br> */<br>@SuppressWarnings(&quot;unused&quot;)<br>private fun hideNotification() {<br>    uiDevice.swipe(<br>            200,<br>            200,<br>            200,<br>            100,<br>            5<br>    )<br>}</pre><h3>Verification essential parts of notification</h3><p>We can verify the content of our notification with Espresso and UiAutomator frameworks because notification is a part of a system and we cannot verify it with Espresso. Here we click on <em>“SEND NOTIFICATION”</em> button with Espresso framework and verify the content of notification with UiAutomator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuWtNFctcpIVajBaKLO-zQ.png" /><figcaption>Verification essential parts of notification</figcaption></figure><pre>private val uiDevice by lazy { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) }<br><br><br>@Rule @JvmField<br>val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)<br><br><br>@Test<br>fun shouldSendNotificationWhichContainsTitleTextAndAllCities() {<br>    val expectedAppName = activityRule.activity.getString(R.string.app_name)<br>    val expectedAllCities = activityRule.activity.getString(R.string.notification_action_all_cities)<br>    val expectedTitle = activityRule.activity.getString(R.string.notification_title)<br>    val expectedText = DummyData.getCityById(amsterdamId).description<br><br>    onView(withId(R.id.list))<br>            .perform(actionOnItemAtPosition&lt;CityViewHolder&gt;(firstItemPos, clickOnSendNotification()))<br><br>    uiDevice.openNotification()<br>    uiDevice.wait(Until.hasObject(By.textStartsWith(expectedAppName)), timeout)<br>    val title: UiObject2 = uiDevice.findObject(By.text(expectedTitle))<br>    val text: UiObject2 = uiDevice.findObject(By.textStartsWith(expectedText))<br>    val allCities: UiObject2 = uiDevice.findObject(By.res(expectedAllCitiesActionRes))<br>    assertEquals(expectedTitle, title.text)<br>    assertTrue(text.text.startsWith(expectedText))<br>    assertEquals(expectedAllCities.toLowerCase(), allCities.text.toLowerCase())<br><br>    clearAllNotifications()<br>}</pre><h3>Verification tap on notification</h3><p>When we click on the notification, we should open the information about city. It means that we can use Espresso and UiAutomator for verification of this case. First of all, we should send notification and open notification area. Later on, we should find our notification by text and click on it. Finally, we can verify information about the city inside the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzlPDxnU_CZY9oYCWD2j8g.png" /><figcaption>Verification tap on notification</figcaption></figure><pre>private val uiDevice by lazy { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) }<br><br><br>@Rule @JvmField <br>val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)<br><br><br>@Test<br>fun shouldClickOnNotificationOpenDetailsScreen() {<br>    val expectedAppName = activityRule.activity.getString(R.string.app_name) <br>    val expectedText = DummyData.getCityById(amsterdamId).description<br>    val expectedSource = activityRule.activity.getString(R.string.source)<br>    onView(withId(R.id.list))<br>            .perform(actionOnItemAtPosition&lt;CityViewHolder&gt;(firstItemPos, clickOnSendNotification()))<br><br>    uiDevice.openNotification()<br>    uiDevice.wait(Until.hasObject(By.textStartsWith(expectedAppName)), timeout)<br>    val text: UiObject2 = uiDevice.findObject(By.textStartsWith(expectedText))<br>    text.click()<br>    uiDevice.wait(Until.hasObject(By.text(expectedText)), timeout)<br><br>    onView(withId(R.id.description_textView))<br>            .check(matches(withText(expectedText)))<br><br>    onView(withId(R.id.source_textView))<br>            .check(matches(withText(expectedSource)))<br>}</pre><h3>Verification tap on an action</h3><p>Actions are the powerful mechanism of notifications. In our case, we have an <em>“ALL CITY”</em> action which opens the list with all cities. The steps for verification are pretty similar to the previous case, and finally, we can check part of the main screen. A unique part of the list of cities is a button <em>“Send all notification as a bundle”</em>. However, we can check that our list contains all needed cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjYaT-a7WHRWO0brMb5ihw.png" /><figcaption>Verification tap on an action</figcaption></figure><pre>private val uiDevice by lazy { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) }<br><br><br>@Rule @JvmField <br>val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)<br><br><br>@Test<br>fun shouldClickOnAllCitiesOpenAllCitiesList() { <br>    val expectedAppName = activityRule.activity.getString(R.string.app_name)<br>    val allNotificationAsBundleText: String =<br>            activityRule.activity.getText(R.string.title_send_all_notifications).toString()<br><br>    onView(withId(R.id.list))<br>            .perform(actionOnItemAtPosition&lt;CityViewHolder&gt;(firstItemPos, clickOnSendNotification()))<br><br>    uiDevice.pressBack()<br><br>    uiDevice.openNotification()<br>    uiDevice.wait(Until.hasObject(By.textStartsWith(expectedAppName)), timeout)<br>    val allCities: UiObject2 = uiDevice.findObject(By.res(expectedAllCitiesActionRes))<br>    allCities.click()<br>    uiDevice.wait(Until.hasObject(By.text(allNotificationAsBundleText)), timeout)<br><br>    onView(withId(R.id.send_all_notifications))<br>            .check(matches(withText(R.string.title_send_all_notifications)))<br>}</pre><h3>Verification of the notification bundle</h3><p>Notification can be grouped for better UX and readability on different devices. We should swipe for bundle notification for expanding list of notifications in this bundle. It means that after notification verification we can swipe down and verify one of notification with click on this notification for checking information about the city.</p><blockquote>I commented <strong>hideNotification()</strong> because it depends on your way of working with floating notification.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4uOpCAyJCw-unAVwdMr8Q.png" /><figcaption>Verification of the notification bundle</figcaption></figure><pre>private val uiDevice by lazy { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) }<br><br><br>@Rule @JvmField <br>val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)<br><br><br>@Test<br>fun shouldClickOnFirstNotificationOfNotificationBundle() {<br>    val expectedAppName = activityRule.activity.getString(R.string.app_name) <br>    val expectedText = DummyData.getCityById(amsterdamId).description<br>    <br>    onView(withId(R.id.send_all_notifications))<br>            .perform(click())<br><br>    /*hideNotification()*/<br>    uiDevice.openNotification()<br>    uiDevice.wait(Until.hasObject(By.textStartsWith(expectedAppName)), timeout)<br>    val notificationHeader: UiObject2 = uiDevice.findObject(By.res(notificationHeaderRes))<br>    notificationHeader.swipe(Direction.DOWN, 0.05f)<br><br>    val amsterdamNotification: UiObject2 = uiDevice.findObject(By.text(expectedText))<br>    amsterdamNotification.click()<br>    uiDevice.wait(Until.hasObject(By.text(expectedText)), timeout)<br><br>    onView(withId(R.id.description_textView))<br>            .check(matches(withText(expectedText)))<br><br>    clearAllNotifications()<br>}</pre><h3>Verification the notification badge feature</h3><p>“Notification badge” feature allows us to long press the icon and see a notification near the icon. We should open all applications and find our application icon. Afterwards, we should long press on the icon, and finally, we can click on notification and verify the behaviour of interacting with notification.</p><blockquote>I commented <strong>hideNotification()</strong> because it depends on your way of working with floating notification.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WB3csxvXNtEhjfn2Icd5Yw.png" /><figcaption>Verification the notification badge feature</figcaption></figure><pre>private val uiDevice by lazy { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) }<br><br><br>@Rule @JvmField <br>val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)<br><br><br>@Test<br>fun shouldClickOnAppIconAndVerifyNotificationBadge() {<br>    val expectedAppName = activityRule.activity.getString(R.string.app_name) <br>    val expectedText = DummyData.getCityById(amsterdamId).description<br>    val allAppsLauncherRes = &quot;com.google.android.apps.nexuslauncher:id/drag_indicator&quot;    <br><br>    onView(withId(R.id.list))<br>            .perform(actionOnItemAtPosition&lt;CityViewHolder&gt;(firstItemPos, clickOnSendNotification()))<br><br>    uiDevice.pressHome()<br>    /*hideNotification()*/<br>    val allApps : UiObject2 = uiDevice.findObject(By.res(allAppsLauncherRes))<br>    allApps.click()<br><br>    uiDevice.wait(Until.hasObject(By.text(expectedAppName)), timeout)<br>    val app: UiObject2 = uiDevice.findObject(By.text(expectedAppName))<br>    app.longClick()<br><br>    val amsterdamNotification: UiObject2 = uiDevice.findObject(By.text(expectedText))<br>    amsterdamNotification.click()<br>    uiDevice.wait(Until.hasObject(By.text(expectedText)), timeout)<br>    onView(withId(R.id.description_textView))<br>            .check(matches(withText(expectedText)))<br>}</pre><p>I described the most popular use cases which we should check if we want to test sending and interacting with notifications.</p><h3>Resources</h3><ul><li><a href="http://alexzh.com/tutorials/notification-for-android/">Guide: Android notifications</a></li><li><a href="https://developer.android.com/training/testing/espresso/">Espresso, official webpage</a></li><li><a href="http://alexzh.com/tutorials/android-testing-espresso-part-3/">Espresso tutorial</a></li><li><a href="https://developer.android.com/training/testing/ui-automator">UiAutomator, official webpage</a></li><li><a href="http://alexzh.com/tutorials/android-testing-ui-automator-part-4/">UiAutomator, tutorial</a></li></ul><blockquote>This article was originally posted on my blog (<a href="http://alexzh.com/">http://alexzh.com/</a>)</blockquote><p><em>Thanks for reading this article. For more about Android development and testing, follow me and visit </em><a href="http://alexzh.com/"><em>my blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f147a572b257" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/testing-android-notifications-f147a572b257">Testing Android Notifications</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data classes in Kotlin]]></title>
            <link>https://medium.com/@Alex_Zhukovich/data-classes-in-kotlin-part-1-fc65ad60a0b1?source=rss-ed1ac4ed780a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc65ad60a0b1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alex Zhukovich]]></dc:creator>
            <pubDate>Sat, 03 Jun 2017 11:34:44 GMT</pubDate>
            <atom:updated>2017-06-14T17:39:28.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIKd5HugXSUl-qsUJfCi0Q.png" /></figure><p>Google announced Kotlin as official language for Android development. One of the greatest feature of Kotlin is that you do not need to rewrite existing projects to Kotlin, you can just continue working on an existing Java project and add new feature.</p><p>Today I would like to suggest how to start working with Kotlin in your project and replace part of existing Java code fast. This small change is fully compatible with Java. It allows you to reduce the amount of Java code and make it simpler to support.</p><p>One of things, which you can find in almost every project, are POJO classes. These classes contain state of an object.</p><p>For instance, we have simple class Person which contains: id, name and age of a person. This code looks the following way In Java:</p><pre>public class Person {</pre><pre>    private int id;<br>    private String name;1<br>    private int age;</pre><pre>    public Person(int id, String name, int age) {<br>        this.id = id;<br>        this.name = name;<br>        this.age = age;<br>    }</pre><pre>    public int getId() {<br>        return id;<br>    }</pre><pre>    public void setId(int id) {<br>        this.id = id;<br>    }</pre><pre>    public String getName() {<br>        return name;<br>    }</pre><pre>    public void setName(String name) {<br>        this.name = name;<br>    }</pre><pre>    public int getAge() {<br>        return age;<br>    }</pre><pre>    public void setAge(int age) {<br>        this.age = age;<br>    }</pre><pre>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;</pre><pre>        Person person = (Person) o;</pre><pre>        if (id != person.id) return false;<br>            if (age != person.age) return false;<br>            return name != null ? name.equals(person.name) : person.name == null;<br>    }</pre><pre>    @Override<br>    public int hashCode() {<br>        int result = id;<br>        result = 31 * result + (name != null ? name.hashCode() : 0);<br>        result = 31 * result + age;<br>        return result;<br>    }</pre><pre>    @Override<br>    public String toString() {<br>        return &quot;Person{&quot; +<br>                &quot;id=&quot; + id +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, age=&quot; + age +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>This code does nothing , except storing status of an object. Here we have few overrided methods:</p><ul><li>public boolean <strong>equals</strong>(Object o)<br>This method is needed for comparing objects.</li><li>public int <strong>hashCode</strong>()<br>This method is needed for using an object with Collection framework.</li><li>public String <strong>toString</strong>()<br>This method is needed for using String representation of the object.</li></ul><p>You can replace the whole class with just one line in Kotlin:</p><pre>data class Person(var id: Int, var name: String, var age: Int)</pre><p>We can decompile Kotlin bytecode and be sure that all these methods were generated and added to bytecode. You can do it from “<strong>Tools</strong> / <strong>Kotlin</strong> / <strong>Show Kotlin Bytecode</strong>” menu and press “<strong>Decompile</strong>”.</p><pre>public final class Person {<br>   private int id;<br>   @NotNull private String name;<br>   private int age;</pre><pre>   public final int getId() {<br>      return this.id;<br>   }</pre><pre>   public final void setId(int var1) {<br>      this.id = var1;<br>   }</pre><pre>   @NotNull<br>   public final String getName() {<br>      return this.name;<br>   }</pre><pre>   public final void setName(@NotNull String var1) {<br>      Intrinsics.checkParameterIsNotNull(var1, &quot;&lt;set-?&gt;&quot;);<br>      this.name = var1;<br>   }</pre><pre>   public final int getAge() {<br>      return this.age;<br>   }</pre><pre>   public final void setAge(int var1) {<br>      this.age = var1;<br>   }</pre><pre>   ...</pre><pre>   public String toString() {<br>      ...<br>   }</pre><pre>   public int hashCode() {<br>      ...<br>   }</pre><pre>   public boolean equals(Object var1) {<br>      ...<br>   }<br>}</pre><p>Creating of new objects:</p><pre>var andy = Person(1, &quot;Andy&quot;, 100)<br>var alex = Person(id = 2, name = &quot;Alex&quot;, age = 100)</pre><p>We can also add default values for each parameter of primary constructor:</p><pre>data class Person(var id: Int = 0, <br>                  var name: String = &quot;User&quot;, <br>                  var age: Int = 100)</pre><p>It means that you can create an object without defining all parameters:</p><pre>var henry = Person(name = &quot;Henry&quot;)</pre><p>Java constructor has 3 parameters and if you want to create all possible constructors for Java, you should update the class a bit.</p><pre>data class Person @JvmOverloads constructor(<br>                                      var id: Int = 0, <br>                                      var name: String = &quot;User&quot;, <br>                                      var age: Int = 100)</pre><p>In this case you have the following constructors available from Java code:</p><ul><li>public Person(int id, @NotNull String name, int age)</li><li>public Person(int id, @NotNull String name)</li><li>public Person(int id)</li><li>public Person()</li></ul><p>However, you should remember that it generates additional methods for you, and by default Android has got limitations on the number of methods till 65536.</p><p>As you can see the Person class has getters and setters, because we use variables (“<strong>var</strong>”). However, we can also use values (“<strong>val</strong>”).</p><pre>data class Person(val id: Int, val name: String, val age: Int)</pre><p>After these changes class will just have getters</p><pre>public final class Person {<br>   private final int id;<br>   @NotNull private final String name;<br>   private final int age;</pre><pre>   public final int getId() {<br>      return this.id;<br>   }</pre><pre>   @NotNull<br>   public final String getName() {<br>      return this.name;<br>   }</pre><pre>   public final int getAge() {<br>      return this.age;<br>   }</pre><pre>   public Person(int id, @NotNull String name, int age) {<br>      Intrinsics.checkParameterIsNotNull(name, &quot;name&quot;);<br>      super();<br>      this.id = id;<br>      this.name = name;<br>      this.age = age;<br>   }</pre><pre>   ...</pre><pre>   @NotNull<br>   public final Person copy(int id, @NotNull String name, int age) {<br>      ...<br>   }</pre><pre>   public String toString() {<br>      ...<br>   }</pre><pre>   public int hashCode() {<br>      ...<br>   }</pre><pre>   public boolean equals(Object var1) {<br>      ...<br>   }<br>}</pre><p>Sometimes you want to create a new object that is almost the same as an existing object, and in case of immutable class you can use <strong>copy()</strong> function.</p><pre>val andy = Person(1, &quot;Andy&quot;, 25)<br>val andy2 = andy.copy(id = 2, age = 27)</pre><p>We can also use inheritance with data classes. However, we should remember that all classes are final by default, therefore we need to be sure that the base class is open.</p><pre>sealed class Report {<br>        abstract val date: Long<br>}<br>    <br>data class Employee(<br>        var name: String, <br>        var age: Int, <br>        override val date: Long) : Report()</pre><p>Here we used sealed class, this type of classes are used for representing class hierarchy.</p><p><em>Thanks for reading this article. For more about Android development and testing, follow me and visit </em><a href="http://alexzh.com/"><em>my blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc65ad60a0b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>