<?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 Augustine Kwong on Medium]]></title>
        <description><![CDATA[Stories by Augustine Kwong on Medium]]></description>
        <link>https://medium.com/@augustine.kwong?source=rss-17fb0d531811------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zP9jSUe6ZWeechT1</url>
            <title>Stories by Augustine Kwong on Medium</title>
            <link>https://medium.com/@augustine.kwong?source=rss-17fb0d531811------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:01:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@augustine.kwong/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[Mocking in In-App Purchase UI Tests — Mockito, Dagger2 and Espresso]]></title>
            <link>https://medium.com/hootsuite-engineering/mocking-in-in-app-purchase-ui-tests-mockito-dagger2-and-espresso-dad393e749c0?source=rss-17fb0d531811------2</link>
            <guid isPermaLink="false">https://medium.com/p/dad393e749c0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[billing]]></category>
            <dc:creator><![CDATA[Augustine Kwong]]></dc:creator>
            <pubDate>Fri, 31 Aug 2018 21:37:23 GMT</pubDate>
            <atom:updated>2018-08-31T21:37:23.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*yLeEpnbNSHL7BIvX" /></figure><p>Testing In-App Purchase (IAP) flow is especially difficult — completing the flow produces side effects that are hard to reverse, e.g. upgrading a user or making a purchase, so it makes sense to mock these calls even in a UI test. In this article we will create Espresso UI Instrumented tests for Android that will proceed through the IAP, mocking the responses from Google Billing and our own user database.</p><p><strong>The stack</strong></p><ul><li><a href="https://developer.android.com/training/testing/espresso/">Android Espresso Test Framework</a></li><li><a href="https://github.com/google/dagger">Dagger 2 Dependency Injection</a></li><li><a href="https://site.mockito.org/">Mockito 2</a></li></ul><p><strong>The process</strong></p><p>Create directory your/folder/location/src/androidTest. It should be on the same level as src/main.</p><p>Within this directory, mirror your src/main/ directory structure.</p><ol><li>Create a test DaggerComponent in /androidTest/com/domain/.../dagger, one that will supply our mocked dependencies.</li><li>Create a test DaggerApplication, one that will receive our mocked modules.</li><li>Create a test runner that uses our test application.</li><li>Write tests! Run with the test runner.</li></ol><h3><strong>Step one — Dagger Component</strong></h3><p>A quick overview of Dagger2. In order to provide dependencies:</p><ol><li>Specify module classes that provide objects of a certain class type. The class is annotated with @Module and methods are annotated with @Provides. The names don’t matter and are just convention. The return type of the method is what’s used in the graph. For tests, it is useful to annotate all @Provides with @Singleton</li></ol><pre>@Module<br>class MockAppModule {</pre><pre>   @Provides<br>   @Singleton<br>   fun provideUserManager = UserManager()</pre><pre>   @Provides<br>   @Singleton<br>   fun provideApi = mock(Api::class.java)</pre><pre>}</pre><p>2. Specify a Component; An adapter between your modules and your injected fields. @Components can be built and injected into different contexts to provide injected fields.</p><pre>@Component(modules = arrayOf(MockAppModule::class))<br>@Singleton<br>interface MockComponent : AndroidInjector&lt;TestApplication&gt; {</pre><pre>    fun inject(tests: ApplicationUITests)</pre><pre>}</pre><p>There are 2 new additions we will ignore for the time being, TestApplication and the inject method.</p><h3>Step Two — Create a test application</h3><p>Our tests have a different dependency graph than our production application. Create a test application that uses our test dependency graph.</p><pre>class TestApplication : DaggerApplication() {<br><br>    lateinit var component: TestComponent<br><br>    override fun applicationInjector(): AndroidInjector&lt;out DaggerApplication&gt; = DaggerTestComponent<br>            .builder()<br>            .build()<br>            .also <strong>{ </strong>component = it <strong>}<br></strong>}</pre><p>For Dagger to recognize that the annotations in TestComponent needs to be generated into a TestComponent, add to your build.gradle</p><pre>kaptAndroidTest &quot;com.google.dagger:dagger-compiler:$daggerVersion&quot;<br>kaptAndroidTest &quot;com.google.dagger:dagger-android-processor:$daggerVersion&quot;</pre><h3>Step Three — Specify an instrumented test runner</h3><pre>class TestApplicationRunner: AndroidJUnitRunner() {</pre><pre>    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?) = Instrumentation.newApplication(TestApplication::class.<em>java</em>, context)<br>   <br>}</pre><p>Set this as the Instrumented Test Runner in build.gradle of your app. Make sure you have:</p><pre>android {<br>    defaultConfig {<br>        testInstrumentationRunner &quot;com.your.app.domain.TestApplicationRunner&quot;<br>    }<br>}</pre><h3>Step Four — The test class</h3><p>We’re mostly done. Only the classes in our modules that return mocks will be mocked. Within our test class, retrieve the TestAppplication’s component. Having used @Singleton for the dependencies will allow us to retrieve the same instances to mock certain calls.</p><p>In our test class, annotate the mocked classes and inject the test application’s singletons. We stub methods accordingly.</p><pre>class ApplicationUITests {<br><br>    @get:Rule<br>    @Suppress(&quot;unused&quot;)<br>    internal var mockitoRule = MockitoJUnit.rule()<br><br>    @get:Rule<br>    var activityTestRule = ActivityTestRule&lt;PaywallActivity&gt; .(PaywallActivity::class.java, true, true)</pre><pre>    @Inject<br>    internal lateinit var userManager: UserManager<br>    <br>    val user = mock(User::class.java).apply {<br>        /* return a real user or mock the properties here */<br>    }</pre><pre>    @Before<br>    fun setupMocks() {<br>        `when`(userManager.getUser()).thenReturn(user)<br>    }</pre><pre>    @Test<br>    fun enterActivity_showsInfo() {<br>        onView(withText(&quot;Hello World&quot;)).check(matches(isDisplayed()))<br>    }<br>}</pre><h3>Conclusion</h3><p>Here are some considerations</p><ul><li>If you are also using Kotlin, you can only mock interfaces. This should be fine since all APIs should have an interface layer regardless</li><li>If you are having issues with asynchronous code that uses a loosely defined callback flow, consider using Espresso Idling Resources. The official documentation code says to embed idling resource calls in production code. There is no need for that, just use them inside your mocked calls.</li><li>Use the right tool for the job; this is a very specific use case so thoroughly consider whether methods need to be mocked in a UI test.</li></ul><p>In general, use UI tests to ensure that core flows maintain their functionality. They are an integration <em>and</em> regression test. Adding stub methods when testing this flow is a consideration that shouldn’t be taken lightly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*9JUJjFaLrVikKjBBSc-yYw.jpeg" /></figure><h4>About the author</h4><p><a href="http://www.linkedin.com/in/augustinekwong">Augustine Kwong</a> is a Combined Major in Computer Science and Statistics at the University of British Columbia. He worked on the Core Mobile team, working predominantly on the Android app but branched out to work on backend in Scala.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad393e749c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hootsuite-engineering/mocking-in-in-app-purchase-ui-tests-mockito-dagger2-and-espresso-dad393e749c0">Mocking in In-App Purchase UI Tests — Mockito, Dagger2 and Espresso</a> was originally published in <a href="https://medium.com/hootsuite-engineering">Hootsuite Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimistic Updates with RxKotlin and ItemTouchHelper (Android)]]></title>
            <link>https://medium.com/hootsuite-engineering/optimistic-updates-with-rxkotlin-and-itemtouchhelper-android-12e904b3c5ff?source=rss-17fb0d531811------2</link>
            <guid isPermaLink="false">https://medium.com/p/12e904b3c5ff</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Augustine Kwong]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 21:53:58 GMT</pubDate>
            <atom:updated>2018-08-31T21:39:59.118Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most frustrating and rewarding features I worked on during my co-op was reworking a settings page for users that featured drag-and-drop and optimistic updates. The problems that arose showed me the subtle complexities of such a feature. They also cautioned me to write simpler, readable (and ergo debuggable) code so design flaws are less often confused with technical bugs.</p><h3>General use case: Manage groups of ordered items, where individual items can be moved between groups</h3><blockquote><strong>User Story</strong><br>As an Android Hootsuite user, I want to be able to <strong>control </strong>the content that is displayed to me. To that end, I should be able to <strong>group</strong> related social networks/streams together into tabs and <strong>rearrange</strong> the <strong>order</strong> of tabs as well as the streams within each tab so that the highest priority content streams are easily accessible and related content is grouped to my liking.</blockquote><p><em>(content) streams</em> :: Each social network (SN) provides different content sources. For example if you add a Twitter account, you might have a “My Posts” stream (featuring all your posts), or you can define your own by <a href="https://help.hootsuite.com/hc/en-us/articles/204596660-Add-move-edit-refresh-or-delete-streams-Android">defining a search</a> for a hashtag/query.</p><p><em>tab</em> :: A grouping of content streams. Loading a tab will allow you to swipe across all the contained streams.</p><p><strong>Problem Overview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*w--kueafq8kRKVLtBpXOVg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*dNN2ue7x0CvXpXu9jyGUbA.gif" /><figcaption>(Left) Old tabs and streams management (Right) New tabs and streams management — what we’re building</figcaption></figure><p>Here’s a detailed breakdown of the features:</p><ul><li>A list of heterogeneous items — Tabs (category headers), Streams (item), Empty Placeholder (prompts user to Add Stream if Tab is empty), Footers (user dependent)</li><li>Tabs that contain no Streams instead have a placeholder which performs the same function as “add stream” from the Tab overflow menu</li><li>Footers with their own actions that are appended to the very bottom of the list</li><li>Popup overflow menu on each Tab item to: add stream, rename, reorder, delete</li><li>Drag handle/long-press on Stream that allows dragging and dropping</li><li>Left swipe on Stream to remove it from the Tab</li></ul><p>Before redesigning this functionality, our existing implementation featured some but not all of these features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*w--kueafq8kRKVLtBpXOVg.gif" /></figure><p>In addition to discoverability issues, a main source of gripe is the blocking ProgressDialog (deprecated) on each action. Therefore, it would be nice (but overwhelmingly frustrating for me) to add the following features:</p><ul><li>Non-blocking re-arrange actions (optimistically update UI)</li><li>Snackbar notification with Undo action</li></ul><p>Our implementation prioritizes:</p><ol><li><strong>Maintainability and Extensibility </strong>— this is the most important technical lesson I learned during my co-op. Maintainability means writing code knowing that someone else will have to dig through it at some point to change/add functionality. As the cliche goes: there’s readable code and then there’s code that no one uses.</li><li><strong>Smoothness </strong>— we are relying heavily on touch interactions to effect state changes. We want to avoid instances such as forcing the user to drop a held item when we refresh/display a snackbar or needlessly refreshing the display and blocking user interaction.</li></ol><p><strong>Android UI components</strong></p><p>From the problem overview, we can already gain a sense of the UI components we’ll need.</p><p><em>A list of heterogeneous items: </em>A RecyclerView with multiple view types and view holders. We maintain an RecyclerView.Adapter&lt;Any&gt;; we forego adding an additional layer of abstraction e.g.RecyclerView&lt;ManageItem&gt; as there is no real added benefit. We will still leverage getItemViewType regardless. Our code base already abstracts the onBindViewHolder and onCreateViewHolder into a superclass with a SAM interface that handles interaction callbacks.</p><p><em>View interactions specific to view type: </em>As mentioned above, our SAM interface will handle any effectful interactions.</p><p><em>Swipe-to-Delete and Drag-and-Drop: </em>Use the ItemTouchHelper to animate and handle these interactions.</p><p><strong>Architecture Pattern</strong></p><p>First things first — what view architecture would make our lives easier? Lately, we’ve been moving more towards the Model-View-ViewModel (MVVM) architecture for Android features at Hootsuite. Here are several reasons why I believe this is the best pattern for this use case:</p><ul><li>Well-supported by Android Framework, retention of state through <a href="http://code.hootsuite.com/orientation-changes-on-android/">orientation change</a>.</li><li>Separation of business logic from the view, making complex transformations easily unit testable. When we make/undo a change, repopulating the data or reverting failure states can be individually tested. We have full control over the data model and don’t need to programmatically trigger drag/drops or swipes.</li><li>Abstracting common logic between similar use cases. Re-ordering Tabs has much of the same logic as re-ordering Streams (albeit much simpler).</li><li>Already high coupling required on View. Our custom RecyclerView already has interaction listeners to support Swipe-to-Refresh and Jump-to-Top. Each list item may have additional view interactions. We will also be adding ItemTouchHelper. Can we centralize this responsibility?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*z_WwjV6hXY4D3MSQv-F06g.png" /><figcaption>Simplified UML class diagram of implementation. Several classes omitted.</figcaption></figure><p>With optimistic updates, it would be nice to have a single-source of truth for UI state. MVC might do. But consider the fact that some changes to the model e.g. database update, do not reflect instantly on the view because we’re updating them optimistically and asynchronously. We want an intermediary for any change. In combination with Rx, ViewModel’s are up to the task! They will allow us to reactively coordinate changes from a multitude of view interactions.</p><h3>Maintainability</h3><p>I was delighted to find that our existing code base had an excellent abstraction for handling many different list item layouts in a single list (RecyclerView). The more interesting and challenging consideration was writing readable code; readability distinguishes easily maintainable and debuggable code from giant swamps of degrading code quality.</p><p>Here is an example where I made a tradeoff between the (negligible) space complexity of modifying a list in-place with the readability of more expressive code, taking advantage of Kotlin syntax.</p><p>The purpose of the functions are the same: given a list of items, we want to insert empty placeholders or remove them from the appropriate places. E.g. two Tabs in a row indicate one of them is empty and a placeholder should be inserted. We write it as an extension function since it is always used in the context of our list of data, thus we implicitly assign it the responsibility of re-arranging itself correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ca06ec75790e218a13b42a23afb3fe8/href">https://medium.com/media/8ca06ec75790e218a13b42a23afb3fe8/href</a></iframe><h4>Disgusting. It really is. But it totally works. What’s so bad about it?</h4><ul><li>It assumes familiar knowledge of the iterator cursor. When you insert an item, where does it go? What gets removed?</li><li>Peeking ahead is impossible with our cursor, we have to advance to check the condition and retreat to perform certain actions</li><li>Nested ifs inside a switch statement inside a loop.</li></ul><p>Overall, the problem is this: the context of each line is hard to gleam from line to line. Where are we in the list? Where is the cursor? Where do we need the cursor to be in order to remove this item? In sum, <strong>in-place relies on side-effects. Side effects are sometimes hard to keep-track of and read.</strong></p><p>Let’s try a slightly different, more functional fold approach; though not in-place, both implementations are still O(n).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e0aa509ed7481e244db88cc89cbaad7/href">https://medium.com/media/6e0aa509ed7481e244db88cc89cbaad7/href</a></iframe><h4>Why do I consider this implementation superior?</h4><p>For those unfamiliar with the fold method, here’s a quick review. Fold is a lot like a for-each loop, except that it returns a single value. Think of it as initializing an “accumulator” variable, and for each item in the collection, you will place into it a new value. At the very end, the value inside your accumulator is returned. Here are a few examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20dcbd6d41637e510bbdd8ae424ee475/href">https://medium.com/media/20dcbd6d41637e510bbdd8ae424ee475/href</a></iframe><p>With our fold implementation, we are able to leverage the Kotlin’s syntax to improve readability. As <a href="http://code.hootsuite.com/?s=trevor+stokvis">Trevor Stokvis</a> reminded me in conversation, it’s often useful to use <em>method names as documentation</em>. Here, the purpose of these functions are very clear. In fact, they even clarify the context at their call-site — something that we lost with the indexing of the iterator.</p><p>Finally, we can read the code in a simpler way: we are progressing through our list, slowly accumulating certain items. We don’t have to worry about backtracking and removing elements.</p><h3><strong>Smoothness</strong></h3><p>An important UX consideration is what to do when our optimism succeeds, i.e. the server accepts our change request.</p><p>One way to do optimistic updates is to allow the state change and further actions, and when the success response is received, we update the screen to the successful state.</p><p>Below is a demo on Android and iOS. In both, we are rearranging streams between and within a category. On the right, we see what happens when we re-draw the screen when our optimistic update query returns successfully. On the left is where we silently accept the success and don’t interrupt the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*6I-l0tHbKnJVGtWXl9u2eg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*cnygmpxj5fUVHmmyU7-nqA.gif" /><figcaption>(Left) Android; (Right) iOS</figcaption></figure><p>In other words, the iOS implementation will <strong>replay successful actions,</strong> which interrupts the user and acts as a pseudo-blocking state.</p><p>What we want to do is <strong>only revert failure states</strong>. This means that we should be even <em>more optimistic</em>. This is where the big headache begins. We should be able to base our changes off uncommitted states, that we hope will soon be committed.</p><h3>Action States</h3><p>We convey the change using an PublishSubject that emits a sealed class</p><pre>sealed class DataEvent(val data: List&lt;Any&gt;) {<br>    class RefreshSuccess : DataEvent()<br>    ...<br>}</pre><pre>val subject: PublishSubject&lt;DataEvent&gt; = PublishSubject.create()</pre><p>Then we define the different event states possible: RefreshSuccess, RefreshFailure, MovePending, MoveSuccess, MoveFailure, UndoPending, UndoSuccess, UndoFailure. This makes it easy to view each action flow as a series of finite-states, where the transition functions can be user input or api calls/responses. When testing the view model, we can mock/invoke these transitions between states and verify the result emitted by the view model subject.</p><p>The MoveSuccess is an interesting special case, since it’s meant to be “undoable”. We need to record the previous state as well as the desired state. Depending on your server endpoint, you have to consider how to reverse the state change. If all the logic is server-side, then you’re in luck! Sadly this wasn’t the case and the inverse move action had to be computed, sent, and handled.</p><h3>Conclusion</h3><p>This setup is quite flexible to extending functionality.</p><ul><li>The ItemViews themselves are modularized, they can be re-skinned and have their actions changed</li><li>The ItemTouchHelper can be modified to support swipe actions</li><li>Business logic lives exclusively in the ViewModel, changes will be localized and testing the view model covers most use cases</li></ul><p>There are some considerations to make though:</p><ul><li>There is a lot of code due to all the different actions that can be performed on the screen. A screen as complex as this might be divided and simplified.</li><li>This ‘optimism’ flow can be entirely circumvented by using an “edit” mode with “done” button that commits the changes, depends on the use case.</li></ul><p>Though I ran into many dead-ends and questions that led to more questions, slowly working through and iterating an implementation was incredibly rewarding. It wasn’t so much writing the code that tripped me up, the main consideration was modularizing each piece so that it could be changed or added to. An unexpected side effect was that it was much easier to diagnose and improve my solution. Because all the code for a particular functionality had a logical place, it was easy to form hypothesis and work it out.</p><p>That being said, all the credit goes to the amazing UX team and mobile team I had the pleasure of working with here at Hootsuite. The support, patience and cordiality shown to me kept me motivated and excited about implementing from a user-minded perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*9JUJjFaLrVikKjBBSc-yYw.jpeg" /></figure><h4>About the author</h4><p><a href="http://www.linkedin.com/in/augustinekwong">Augustine Kwong</a> is a Combined Major in Computer Science and Statistics at the University of British Columbia. He worked on the Core Mobile team, working predominantly on the Android app but branched out to work on backend in Scala.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12e904b3c5ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hootsuite-engineering/optimistic-updates-with-rxkotlin-and-itemtouchhelper-android-12e904b3c5ff">Optimistic Updates with RxKotlin and ItemTouchHelper (Android)</a> was originally published in <a href="https://medium.com/hootsuite-engineering">Hootsuite Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>