<?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 Evan Chen on Medium]]></title>
        <description><![CDATA[Stories by Evan Chen on Medium]]></description>
        <link>https://medium.com/@evanchen7623?source=rss-ffa369df87fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pj4ytIurJTQTwvGxwx2brQ.jpeg</url>
            <title>Stories by Evan Chen on Medium</title>
            <link>https://medium.com/@evanchen7623?source=rss-ffa369df87fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:53:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evanchen7623/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android TDD Part 13 — Summary of testing]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-13-summary-of-testing-2e1733175d01?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e1733175d01</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-testing]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Sat, 28 May 2022 03:07:45 GMT</pubDate>
            <atom:updated>2022-05-28T03:07:45.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android TDD Part 13 — Summary of testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkSTNQ-BY5gp3TiVzUc9XA.png" /></figure><p>Let’s summarize the test on Android. Android tests include :</p><ul><li>Local Unit Test</li><li>Local Unit Test by Robolectric</li><li>Instrumented Test</li><li>UI Test</li></ul><h4>Local Unit Test</h4><p>The<strong> </strong>local unit test is the fastest. Always prefer unit tests to others.To write a good unit test, you should separate UI and business logic.</p><h4>Instrumented Test</h4><p>While test subjects are related to the Android framework, you need to use Instrumented tests. These tests are run on emulators or devices.</p><h4>UI Test</h4><p>UI tests focus on user behavior. It also runs on emulators or devices.</p><h4>Local unit test by Robolectric</h4><p>Robolectric provides a way to let you run tests on JVM when you are using Android API.</p><h3>Instrumented tests V.S. UI Test</h3><p>These two tests are both located in the “androidTest” folder and run on emulators or devices. What’s different between Instrumented Tests and UI tests is that UI testing is more specific to user behavior. So if you want to test about SharedPreference, it’s an Instrumented test. If you want to test what users do, it’s a UI test.</p><h3>Espresso V.S. Robolectric</h3><p>Espresso and Robolectric are both used to test UI. What’s different between them is:</p><p><strong>Espresso</strong>: the folder is in “Android Test”.<br><strong>Robolectric</strong>: the folder is in “test”.</p><p><strong>Espresso</strong>: tests run on devices.<br><strong>Robolectric</strong>: tests run on JVM.</p><p>The more significant difference is the behavior of testing. For example, if You have a SignUpActivity and ResultActivity, if sign up successfully, should direct to ResultActivity and display “Sign up success”.Then Espresso and Robolectric will test different items:</p><p><strong>Espresso </strong>: “Sign up success” should shown in ResultActivity. See <a href="https://medium.com/@evanchen7623/android-tdd-part-9-ui-test-espresso-54195cbf913">TDD part 9:Espresso.</a><br><strong>Robolectric</strong> : Intent should be correct. See <a href="https://medium.com/@evanchen7623/android-tdd-part-9-robolectric-1c90ae594f08">TDD part 10: Robolectric</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUQZ9oBaQtZa-skA4YqzIA.png" /></figure><p>Another difference is that UI tests do have “type words” on the app, Robolectric only set the value on EditText. So UI tests will open the keyboard to type words. It’s more close to user behavior. It’s more like a user really do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e1733175d01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LocalDate, LocalTime, LocalDateTime with Java 8 in Android]]></title>
            <link>https://levelup.gitconnected.com/using-localdate-localtime-localdatetime-with-java-8-in-android-6df5097c7393?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df5097c7393</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[localdate]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Wed, 25 May 2022 14:58:20 GMT</pubDate>
            <atom:updated>2022-05-28T16:30:32.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Dealing with Date and time in android, you might use Date(java.util.Date) or Calendar(java.util.Calendar).Now you have a better option: LocalDate in Java 8.</p><p><strong>LocalDate</strong> — A date without a time-zone.<br><strong>LocalTime</strong> — A time without a time-zone.<br><strong>LocalDateTime</strong> — A date-time without a time-zone.<br><strong>ZonedDateTime</strong> — A date-time with a time-zone.<br><strong>Duration</strong> — A time-based amount of time.<br><strong>Period</strong> — A date-based amount of time.</p><p>Writing codes below in android, you will get an error that LocalDate is only available above level 26.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2m0sM4uhtKWxa5lKE9F27w.png" /></figure><h3>Java 8+ API desugaring support</h3><p>upgrade gradle to 4.0.0 (or higher) in your project’s build.gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b53b88d740a918e0d9c0d0c91e35f5e/href">https://medium.com/media/5b53b88d740a918e0d9c0d0c91e35f5e/href</a></iframe><p>Include the following in your app module’s build.gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d613e0ff70bd2db65544bd3d1483a2b/href">https://medium.com/media/9d613e0ff70bd2db65544bd3d1483a2b/href</a></iframe><p>Now you can use LocalDateTime in Java8.</p><h3>LocalDate</h3><p>LocalDate — A date without a time-zone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b084b89cd538d990900f19a71ab32d5/href">https://medium.com/media/4b084b89cd538d990900f19a71ab32d5/href</a></iframe><h3>LocalTime</h3><p>LocalTime — A time without a time-zone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a193398197474bb3d87ed7c1b790baff/href">https://medium.com/media/a193398197474bb3d87ed7c1b790baff/href</a></iframe><h3>LocalDateTime</h3><p>LocalDateTime — A date-time without a time-zone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c96356870399ba322e3ffe1560c48e7c/href">https://medium.com/media/c96356870399ba322e3ffe1560c48e7c/href</a></iframe><p>You can also use LocalDate.parse to obtain a date.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08c709ea55ca01d4d4a427b1bf125e18/href">https://medium.com/media/08c709ea55ca01d4d4a427b1bf125e18/href</a></iframe><p>For specified date format, use DateTimeFormatter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b1b11bdc0023d9559bec1a6d4f9bfe/href">https://medium.com/media/05b1b11bdc0023d9559bec1a6d4f9bfe/href</a></iframe><p>Once you create date-time instance, you can get year, day…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0c0111e5c4e644aedffefd43aed419/href">https://medium.com/media/7e0c0111e5c4e644aedffefd43aed419/href</a></iframe><p>plus one day, week, month</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df9fa472402ec63538c3b363a37ccc1/href">https://medium.com/media/3df9fa472402ec63538c3b363a37ccc1/href</a></iframe><h4>TemporalAdjusters</h4><p>TemporalAdjusters let you quickly to find the first and last day.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff6b07e2709b5efa149a0099ae311ab/href">https://medium.com/media/bff6b07e2709b5efa149a0099ae311ab/href</a></iframe><p>Other TemporalAdjusters:</p><p>dayOfWeekInMonth<br>firstDayOfMonth<br>firstDayOfNextMonth<br>firstDayOfNextYear<br>firstDayOfYear<br>firstInMonth<br>lastDayOfMonth<br>lastDayOfNextMonth<br>lastDayOfNextYear<br>lastDayOfYear<br>lastInMonth</p><p><strong>Comparing two LocalDate</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d737b7d02911a97c46b98f2a0e541980/href">https://medium.com/media/d737b7d02911a97c46b98f2a0e541980/href</a></iframe><h4>Period</h4><p>The Period class uses the units year, month and day to represent a period of time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca6376c42cb0bea35d7c9655c80aca9/href">https://medium.com/media/fca6376c42cb0bea35d7c9655c80aca9/href</a></iframe><h3>Duration</h3><p>Represent more precision interval of time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ad2551ae31f3e89ef2bea03c1fe21b/href">https://medium.com/media/34ad2551ae31f3e89ef2bea03c1fe21b/href</a></iframe><h4>ZonedDateTime</h4><p>ZonedDateTime provides a date-time with zone by using ZoneId.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/048b7ac08161a0dfdc11c91c2d4778ed/href">https://medium.com/media/048b7ac08161a0dfdc11c91c2d4778ed/href</a></iframe><p>You can also get all zone IDs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42aecb5510ae3239607d2582f3a82919/href">https://medium.com/media/42aecb5510ae3239607d2582f3a82919/href</a></iframe><p>With ZonedDateTime, you can compare time from different zone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cea5422cd4891381be2555b6c2aeb3d3/href">https://medium.com/media/cea5422cd4891381be2555b6c2aeb3d3/href</a></iframe><p><strong>Reference</strong>:</p><p><a href="https://developer.android.com/studio/write/java8-support#library-desugaring">https://developer.android.com/studio/write/java8-support#library-desugaring</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eae55cad63fda3b713c20d003e936e4/href">https://medium.com/media/3eae55cad63fda3b713c20d003e936e4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df5097c7393" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-localdate-localtime-localdatetime-with-java-8-in-android-6df5097c7393">Using LocalDate, LocalTime, LocalDateTime with Java 8 in Android</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin extension]]></title>
            <link>https://medium.com/@evanchen7623/kotlin-extension-df83a5e89db6?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/df83a5e89db6</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Thu, 19 May 2022 14:20:42 GMT</pubDate>
            <atom:updated>2022-05-19T14:20:42.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlFpJ5_9RXX97Zg0dYrzSA.png" /></figure><p>You can extend a class with a new function without modifying that class.</p><p>We have a function called dollarFormat that converts numbers to money format. For a function like this, we might write them in the Util class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c064ceece66ac3e6f16b721cad9056a/href">https://medium.com/media/0c064ceece66ac3e6f16b721cad9056a/href</a></iframe><p>Or you have an existing class that you can’t modify. If you want to add a function in this class, you only can inherit this class and add new function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a8c5056e374b54cbf05ada8cce69a3/href">https://medium.com/media/30a8c5056e374b54cbf05ada8cce69a3/href</a></iframe><p>These two are not good practice. Add a lot of functions in Util class will make this class too complicated. And using inherit to add a function for a class that you can’t modify is even worse. So we can use an extension to add a function for an existing class.</p><p>To declare an extension, prefix its name with receiver type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab0d2f7a32676df54d9ae6090cd8ba1/href">https://medium.com/media/5ab0d2f7a32676df54d9ae6090cd8ba1/href</a></iframe><p>You can also extend on a nullable type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9e58a0b93962638cfb64eed6d69ef6/href">https://medium.com/media/4d9e58a0b93962638cfb64eed6d69ef6/href</a></iframe><p>Extension functions for generic type</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca88b8086f29cee36497463fd7c08dd/href">https://medium.com/media/4ca88b8086f29cee36497463fd7c08dd/href</a></iframe><p>Kotlin’s standard library like apply and let are generic extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd78fa942e81b614e69cf024976370d6/href">https://medium.com/media/cd78fa942e81b614e69cf024976370d6/href</a></iframe><h4>Extension properties</h4><p>Kotlin support extension properties, for example in the code below, we extension Int to have a square property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e2d7ef38bc31737f32bf313dc5ee10/href">https://medium.com/media/f7e2d7ef38bc31737f32bf313dc5ee10/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df83a5e89db6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 12 — Set test environment variables from Gradle]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-12-set-test-environment-variables-from-gradle-70e18697e006?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e18697e006</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 01:00:28 GMT</pubDate>
            <atom:updated>2022-05-28T03:09:03.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android TDD Part 12 — Set test environment variables from Gradle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkSTNQ-BY5gp3TiVzUc9XA.png" /></figure><p>In this article, we&#39;ll introduce setting a test environment variable from Gradle.</p><h3>ProductFlavor</h3><p>ProductFlavor let you choose different build type when you build your APK. For example, if you have two web APIs, one for production, the other for staging. You can set a production and staging productFlavor. App use production web API when you build a production version, on the contrary, use staging web API. Now, we want to set a prod and mock productFlavors to get different data from the Repository.</p><p>Creates a flavor dimension named &quot;mock&quot; and adds &quot;prod&quot; product flavors.</p><pre>android {<br>  ...<br> productFlavors {<br>  mock {<br>   applicationId &quot;evan.chen.tutorial.tdd.productflavorssample.mock&quot;<br>  }<br>  prod {<br>   applicationId &quot;evan.chen.tutorial.tdd.productflavorssample&quot;<br>  }<br>}<br>flavorDimensions &quot;default&quot;</pre><p>Click <strong>Sync Now</strong> in the notification bar. After the sync completes, you can see 4 build variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nw3sQ9bj5Ber3i2gaNCLiw.png" /></figure><p>Switch mode from <strong>Android</strong> to <strong>Project</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*8xutz0YWzhFI_J81T3PUrg.png" /></figure><p>Create a mock and prod package in the src folder. When you choose mockDebug or mockRelease Build Variant, the Repository in the mock folder will be executed. When you choose prodDebug or prodRelease Build Variant, the Repository in the prod folder will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*RwMChGyxDjtUOnTxC87tYg.png" /></figure><p>Repository in prod folder</p><pre>class Repository {<br>    fun getResult(): String {<br>        return &quot;Result from Remote&quot;<br>    }<br>}</pre><p>Repository in mock folder</p><pre>class Repository {<br>    fun getResult(): String {<br>        return &quot;Result from Mock&quot;<br>    }<br>}</pre><p>When you call repository.getResult on mock build variant, the result is &quot;Result from Mock&quot;. When you call repository.getResult on prod build variant, the result is &quot;Result from Prod&quot;.</p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        val repository = Repository()<br>        val result = repository.getResult()<br>        textView.text = result<br>    }<br>}</pre><h4>Set string of resources</h4><pre>productFlavors {<br>  mock {<br>   applicationId &quot;evan.chen.tutorial.tdd.productflavorssample.mock&quot;<br>   resValue &quot;string&quot;, &quot;name&quot;, &quot;from mock&quot;<br>  }<br>  prod {<br>   applicationId &quot;evan.chen.tutorial.tdd.productflavorssample&quot;<br>   resValue &quot;string&quot;, &quot;name&quot;, &quot;from prod&quot;<br>  }<br>}</pre><p>You can get the string on different product flavor.</p><pre>textView2.text = resources.getString(R.string.name)</pre><h4>Create a sourceSets for test</h4><p>A SourceSet represents a logical group of Java source and resource files. The following codes show adding a java source and resource in sourceSets.</p><pre>sourceSets {<br>    String sharedTestDir = &#39;src/sharedTest/java&#39;<br>    String fakeJsonDir = &#39;src/sharedTest/fakejson&#39;<br><br>    test {<br>        java.srcDir sharedTestDir<br>        resources.srcDirs += fakeJsonDir<br>    }<br>    androidTest {<br>        java.srcDir sharedTestDir<br>        resources.srcDirs += fakeJsonDir<br>    }<br>}</pre><p>Back to project, create a sharedTest folder. This folder only can run in test and androidTest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BPcP5GhUFx6SYHqBExNtPg.png" /></figure><p>Github:<br><a href="https://github.com/evanchen76/AndroidProductflavorsample">https://github.com/evanchen76/AndroidProductflavorsample</a></p><p>Reference:<br><a href="https://developer.android.com/studio/build/build-variants">https://developer.android.com/studio/build/build-variants</a></p><p>Next: Android TDD Part 13 — <strong>Summary of testing</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-13-summary-of-testing-2e1733175d01">Android TDD Part 13 — Summary of testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e18697e006" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 11 — Use custom view to improve testability]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-11-use-custom-view-to-improve-testability-beb1dca171f7?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/beb1dca171f7</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 12:20:50 GMT</pubDate>
            <atom:updated>2020-08-17T01:01:54.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android TDD Part 11 — Use custom view to improve testability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkSTNQ-BY5gp3TiVzUc9XA.png" /></figure><p>You can create a custom view by combining views. For example, this is a number selector, which put a “-” button, “+” button, and Textview, you can pick a number by clicking “+” or “-”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*IHis-p4HJbd4PERJ.png" /></figure><p>The benefit of a custom view is that placing logic in the component. So you only have to test this component, not Activity.</p><h3>Create custom layout</h3><p>Create a NumberSelect layout file. This layout includes a “-” Button, “+” Button, and TextView.</p><pre>&lt;LinearLayout xmlns:android=&quot;&lt;http://schemas.android.com/apk/res/android&gt;&quot;<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:background=&quot;@drawable/number_select_background&quot;&gt;<br>        &lt;Button<br>            android:id=&quot;@+id/minusButton&quot;<br>            android:layout_width=&quot;50dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:padding=&quot;0dp&quot;<br>            android:text=&quot;-&quot;<br>            android:textSize=&quot;32sp&quot; /&gt;<br>        &lt;TextView<br>            android:id=&quot;@+id/valueTextView&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:width=&quot;30dp&quot;<br>            android:gravity=&quot;center&quot;<br>          android:layout_gravity=&quot;center_horizontal|center_vertical&quot;<br>            android:textColor=&quot;@color/colorPrimary&quot; /&gt;<br>        &lt;Button<br>            android:id=&quot;@+id/addButton&quot;<br>            android:layout_width=&quot;50dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:padding=&quot;0dp&quot;<br>            android:text=&quot;+&quot;<br>            android:textSize=&quot;32sp&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><h3>Define custom attributes</h3><p>To define custom attributes, add a declare-styleable resource to your project. you can set default value, minimum value, and maximum value.</p><p>attrs.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;declare-styleable name=&quot;NumberSelect&quot;&gt;<br>        &lt;attr name=&quot;<strong>default_value</strong>&quot; format=&quot;integer&quot; /&gt;<br>        &lt;attr name=&quot;<strong>min_value</strong>&quot; format=&quot;integer&quot; /&gt;<br>        &lt;attr name=&quot;<strong>max_value</strong>&quot; format=&quot;integer&quot; /&gt;<br>    &lt;/declare-styleable&gt;<br>&lt;/resources&gt;</pre><h3>Setting attribute on layout</h3><p>Now you can set defaultValue, minValue and maxValue in custom layout.</p><p>res/layout/activity_main.xml</p><pre>&lt;LinearLayout<br>        xmlns:android=&quot;&lt;http://schemas.android.com/apk/res/android&gt;&quot;<br>        xmlns:tools=&quot;&lt;http://schemas.android.com/tools&gt;&quot;<br>        xmlns:app=&quot;&lt;http://schemas.android.com/apk/res-auto&gt;&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:orientation=&quot;vertical&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        tools:context=&quot;.MainActivity&quot;&gt;<br>    <strong>&lt;evan.chen.tutorial.tdd.customcomponentsample.NumberSelect</strong><br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:id=&quot;@+id/number_select&quot;<br>            app:default_value=&quot;3&quot;<br>            app:min_value=&quot;0&quot;<br>            app:max_value=&quot;20&quot;<br>    <strong>/&gt;</strong><br>&lt;/LinearLayout&gt;</pre><h3>Create NumberSelect Class</h3><p>This class loads layout and initial property by attributes. Provide functions to set max value and min value. We also create a NumberSelectListener interface and onValueChange function. You can implement this interface to know value changed.</p><pre>class NumberSelect : LinearLayout {<br>    private lateinit var addButton: Button<br>    private lateinit var minusButton: Button<br>    private lateinit var valueTextView: TextView<br>    //minimum value<br>    private var minValue: Int = 0<br>    //maximum value<br>    private var maxValue: Int = 0<br>    //default value<br>    private var defaultValue: Int = 0<br>    //now value<br>    var textValue: Int = 0<br>    private var listener: NumberSelectListener? = null</pre><pre>    interface NumberSelectListener {<br>        fun onValueChange(value: Int)<br>    }</pre><pre>    constructor(context: Context) : super(context) {<br>        init(context, null)<br>    }</pre><pre>    constructor(context: Context, attrs: AttributeSet) <br>     : super(context, attrs) {<br>        init(context, attrs)<br>    }</pre><pre>    constructor(context: Context,attrs: AttributeSet, defStyle: Int) <br>     : super(context, attrs, defStyle) {<br>        init(context, attrs)<br>    }</pre><pre>    private fun init(context: Context, attrs: AttributeSet?) {<br>        View.inflate(context, R.layout.number_select, this)<br>        descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS<br>        this.addButton = findViewById(R.id.addButton)<br>        this.minusButton = findViewById(R.id.minusButton)<br>        this.valueTextView = findViewById(R.id.valueTextView)</pre><pre>        this.textValue = 0<br>        this.maxValue = Integer.MAX_VALUE<br>        this.minValue = 0</pre><pre>        if (attrs != null) {<br>            val attributes = context.theme.obtainStyledAttributes(<br>                attrs,<br>                R.styleable.NumberSelect,<br>                0, 0<br>            )</pre><pre>            //get value from layout attributes<br>            this.maxValue = attributes.getInt(<br>              R.styleable.NumberSelect_max_value, this.maxValue<br>            )</pre><pre>            this.minValue =  attributes.getInt(<br>              R.styleable.NumberSelect_min_value, this.minValue<br>            )</pre><pre>            this.defaultValue = attributes.getInt(<br>              R.styleable.NumberSelect_default_value, 0<br>            )</pre><pre>            this.valueTextView.text = defaultValue.toString()<br>            this.textValue = defaultValue<br>        }<br>				<br>       // Click &quot;+&quot; Button,<br>       // set TextValue plus one and call listener.onValueChange<br>      <br>        this.addButton.setOnClickListener {<br>            addTextValue()<br>            if (listener != null) {<br>                listener!!.onValueChange(textValue)<br>            }<br>        }<br>			<br>	// Click &quot;-&quot; Button,<br>        // set TextValue minus one and call listener.onValueChange</pre><pre>        this.minusButton.setOnClickListener {<br>            minusTextValue()<br>            if (listener != null) {<br>                listener!!.onValueChange(textValue)<br>            }<br>        }<br>    }</pre><pre>    fun setMaxValue(value: Int) {<br>        this.maxValue = value<br>    }</pre><pre>    fun setMinValue(value: Int) {<br>        this.minValue = value<br>    }</pre><pre>    fun setDefaultValue(value: Int) {<br>        this.defaultValue = value<br>        this.textValue = value<br>    }</pre><pre>    private fun addTextValue() {<br>        if (this.textValue &lt; this.maxValue) {<br>            this.textValue++<br>            this.valueTextView.text = this.textValue.toString()<br>        }<br>    }</pre><pre>    private fun minusTextValue() {<br>        if (this.textValue &gt; this.minValue) {<br>            this.textValue--<br>            this.valueTextView.text = this.textValue.toString()<br>        }<br>    }<br>    fun setListener(listener: NumberSelectListener) {<br>        this.listener = listener<br>    }<br>}</pre><h3>Use custom component</h3><p>Now you can use NumberSelect in activity_main.xml.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout<br>        xmlns:android=&quot;&lt;http://schemas.android.com/apk/res/android&gt;&quot;<br>        xmlns:tools=&quot;&lt;http://schemas.android.com/tools&gt;&quot;<br>        xmlns:app=&quot;&lt;http://schemas.android.com/apk/res-auto&gt;&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:orientation=&quot;vertical&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        tools:context=&quot;.MainActivity&quot;&gt;<br>    &lt;evan.chen.tutorial.tdd.customcomponentsample.NumberSelect<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:id=&quot;@+id/number_select&quot;<br>            app:default_value=&quot;3&quot;<br>            app:min_value=&quot;0&quot;<br>            app:max_value=&quot;20&quot;<br>    /&gt;<br>&lt;/LinearLayout&gt;</pre><h3>Writing tests</h3><p>First, create NumberSelectAndroidTest in AndroidTest. Add a testAddButtonThenValueShouldAdd test function.</p><p>When “+” button is clicked, textValue should add one.</p><pre>@Test<br>fun testAddButtonThenValueShouldAdd() {<br>    val context = InstrumentationRegistry.getTargetContext()<br>    val numberSelect = NumberSelect(context)<br>    numberSelect.setDefaultValue(1)<br>    numberSelect.addButton.performClick()<br>    Assert.assertEquals(2, numberSelect.textValue)<br>}</pre><p>When “-” button is clicked, textValue should minus one.</p><pre>@Test<br>fun testMinusButtonThenValueShouldMinus() {<br>    val context = InstrumentationRegistry.getTargetContext()<br>    val numberSelect = NumberSelect(context)<br>    numberSelect.setDefaultValue(2)<br>    numberSelect.minusButton.performClick()<br>    Assert.assertEquals(1, numberSelect.textValue)<br>}</pre><p>To verify that textValue can’t less than minValue.</p><pre>@Test<br>fun testMinValueLimit() {<br>    val context = InstrumentationRegistry.getTargetContext()<br>    val numberSelect = NumberSelect(context)<br>    numberSelect.setDefaultValue(2)<br>    numberSelect.setMinValue(2)<br>    numberSelect.minusButton.performClick()<br>    Assert.assertEquals(2, numberSelect.textValue)<br>}</pre><p>To verify that textValue can’t bigger than maxValue.</p><pre>@Test<br>fun testMaxValueLimit() {<br>    val context = InstrumentationRegistry.getTargetContext()<br>    val numberSelect = NumberSelect(context)<br>    numberSelect.setDefaultValue(2)<br>    numberSelect.setMaxValue(2)<br>    numberSelect.addButton.performClick()<br>    Assert.assertEquals(2, numberSelect.textValue)<br>}</pre><p>Github:<br><a href="https://github.com/evanchen76/AndroidTDD_CustomComponent">https://github.com/evanchen76/AndroidTDD_CustomComponent</a></p><p>Reference:<br><a href="https://developer.android.com/guide/topics/ui/custom-components">https://developer.android.com/guide/topics/ui/custom-components</a></p><p>Next: Android TDD Part 12 — <strong>Set test environment variables from Gradle</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-12-set-test-environment-variables-from-gradle-70e18697e006">Android TDD Part 12 — Set test environment variables from Gradle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beb1dca171f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 10— Robolectric]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-9-robolectric-1c90ae594f08?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c90ae594f08</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 14:21:00 GMT</pubDate>
            <atom:updated>2020-08-13T12:22:48.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRU0SlWTlClVfRixlqmipA.png" /></figure><p>We already know running UI and Instrumented tests on devices are slow. There is another way to verify interaction with Android Framework. Robolectric is a framework that brings fast and reliable unit tests to Android. This means you can run your tests on JVM.</p><p>Using the previous register sample. This time, we use Robolectric to test it’s interacting with View.</p><ol><li>When register fail, should alert “Error”</li><li>When register success, should open ResultActivity.</li></ol><p>The production code of the register sample.</p><pre>if (!isLoginIdOK) {<br>    // Register fail<br>    val builder = AlertDialog.Builder(this)<br>    builder.setMessage(<br>    &quot;loginId at least 8 words and first letter should be alphabetized.&quot;)<br>    .setTitle(&quot;Error&quot;)<br>    <strong>builder.show()</strong><br>}<br>else if (!isPwdOK) {<br>    val builder = AlertDialog.Builder(this)<br>    builder.setMessage(<br>    &quot;Password at least 8 words and first letter should be alphabetized.&quot;)<br>    .setTitle(&quot;Error&quot;)<br>    <strong>builder.show()</strong><br>} else {<br>    val intent = Intent(this, ResultActivity::class.java)<br>    intent.putExtra(&quot;ID&quot;, loginId)<br>    <strong>startActivity</strong>(intent)<br>}</pre><p>Create tests to verify:</p><ol><li>Register fail ⇒ alert</li><li>Register success ⇒ open StartActivity</li></ol><h3>Creating a Robolectric Test</h3><p>Add the following to your build.gradle:</p><pre>android{<br>    testOptions.unitTests.includeAndroidResources = true<br>}</pre><pre>dependencies { <br>    testImplementation &quot;org.robolectric:robolectric:4.3&quot;<br>}</pre><p>Create MainActivityTest on your src/test folder. Add an annotation Robolectric test runner on MainActivityTest.</p><pre>@RunWith(RobolectricTestRunner::class)<br>class MainActivityTest {<br>}</pre><p>Initial MainActivity on setupActivity method.</p><pre>private lateinit var activity: MainActivity</pre><pre>@Before<br>fun setupActivity() {<br>    MockitoAnnotations.initMocks(this)<br>    <br>    activity = Robolectric.buildActivity(MainActivity::class.java).setup().get()<br>}</pre><h3>Use shadowActivity to test StartActivity</h3><p>To verify startActivity, follow these steps:</p><p>Step 1. Create a shadowActivity.</p><p>Step 2. Type UserId and Password, then click the send button.</p><p>Step 3. Verify intent.</p><pre>@Test<br>fun registerSuccessShouldDirectToResult() {<br>    <strong>//Step 1. Create shadowActivity</strong><br>    val shadowActivity = Shadows.shadowOf(activity)</pre><pre>    <strong>//Step 2. Type UserId and Password, then click send button.</strong><br>    val userId = &quot;A123456789&quot;<br>    val userPassword = &quot;a123456789&quot;<br>    activity.loginId.setText(userId)<br>    activity.password.setText(userPassword)<br>    activity.send.performClick()</pre><pre>    <strong>//Step 3. Verify intent</strong><br>    val nextIntent = shadowActivity.nextStartedActivity</pre><pre>    //To assert nextIntent&#39;s class should be ResultActivity<br>    assertEquals(<br>      nextIntent.component!!.className<br>      ,ResultActivity::class.java.name)</pre><pre>    //To assert nextIntent&#39;s size is 1<br>    assertEquals(1, nextIntent.extras!!.size())</pre><pre>    //To assert nextIntent&#39;s extra include ID<br>    assertEquals(userId, nextIntent.extras!!.getString(&quot;ID&quot;))<br>}</pre><p>Use ShadowAlertDialog.getLatestDialog() to verify is Dialog shown.</p><pre>@Test<br>fun registerFailShouldAlert() {<br>    <br>    //arrange<br>    val userId = &quot;A1234&quot;<br>    val userPassword = &quot;a123456789&quot;<br>    activity.loginId.setText(userId)<br>    activity.password.setText(userPassword)</pre><pre>    //act<br>    activity.send.performClick()</pre><pre>    //assert<br>    val dialog = ShadowAlertDialog.getLatestDialog()<br>    assertNotNull(dialog)<br>    assertTrue(dialog.isShowing)<br>}</pre><p>Github:<br><a href="https://github.com/evanchen76/AndroidTDD_RobolectricSample">https://github.com/evanchen76/AndroidTDD_RobolectricSample</a></p><p>Reference: <br><a href="http://robolectric.org/">http://robolectric.org/</a></p><p>Next: Android TDD Part 11 — <strong>Use custom view to improve testability</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-11-use-custom-view-to-improve-testability-beb1dca171f7">Android TDD Part 11 — Use custom view to improve testability</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c90ae594f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 9— UI Test: Espresso]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-9-ui-test-espresso-54195cbf913?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/54195cbf913</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 02:18:33 GMT</pubDate>
            <atom:updated>2020-08-08T14:23:48.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRU0SlWTlClVfRixlqmipA.png" /></figure><p>Running UI tests take more time than unit tests, but we still need it. Espresso is an Android UI test framework. you can get a view by id or text, then click a button or type data in an EditText to verify behavior is correct.</p><h3>Find a view</h3><p>Finding a view by its id</p><pre>onView(withId(R.id.someId)).perform(typeText(&quot;Some Text&quot;))</pre><p>Finding a view by matching a text.</p><pre>onView(withText(&quot;Some text&quot;)).check(matches(isDisplayed()))</pre><h3>Clicking a view by its id</h3><pre>onView(withId(R.id.button)).perform(click())</pre><h3>Espresso dependencies</h3><p>Add the following dependencies on app’s build.gradle file.</p><pre>dependencies {<br>    androidTestImplementation &#39;com.android.support.test:rules:1.0.2&#39;<br>    androidTestImplementation &#39;com.android.support.test:runner:1.0.2&#39;<br>    androidTestImplementation &#39;com.android.support.test.espresso:espresso-core:3.0.2&#39;<br>}</pre><h3>Write UI test</h3><p>Use previous sample: sing up.UI test is located at androidTest just like the Instrumented test. Create a RegisterTest class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*weoDbbZk--4GR3Eg.png" /></figure><p>@LargeTest annotation indicates that the test duration can be more than 1 second.</p><pre>@LargeTest<br>class RegisterTest {<br>    <br>}</pre><p>To test MainActivity, use ActivityTestRule to get an Activity instance.</p><pre>class RegisterTest {<br>    @Rule<br>    @JvmField<br>    var activityActivityTestRule <br>      = ActivityTestRule(MainActivity::class.java)<br>}</pre><p>Write a UI test for register success:</p><ol><li>Type a123456789 on loginId.</li><li>Type a111111111 on password.</li><li>Click the send button.</li><li>Verify contains a text “Sign Up Success” on view.</li></ol><pre>@Test<br>fun rightPassword_should_startActivity() {<br>   <br>    //type &quot;a123456789&quot; on loginId<br>    onView(withId(R.id.loginId)).perform(typeText(&quot;a123456789&quot;)<br>      , ViewActions.closeSoftKeyboard())<br>    <br>    //type &quot;a111111111&quot; on password<br>    onView(withId(R.id.password)).perform(typeText(&quot;a111111111&quot;)<br>      , ViewActions.closeSoftKeyboard())</pre><pre>    //click send button<br>    onView(withId(R.id.send)).perform(click())</pre><pre>    //verify screen should display &quot;Sign Up Success&quot;<br>    onView(withText(&quot;Sign Up Success&quot;))<br>      .check(matches(isDisplayed()))<br>}</pre><p>Click the green triangle to run the test. You’ll see the emulator is running test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Q_FCFxKOGsnCYh1n.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*fWksFb1simhrL8PfzH7BOA.gif" /></figure><p>Typing the wrong password should alert.</p><pre>@Test<br>fun wrongPassword_should_alert() {<br>    <br>    //type login id<br>    onView(withId(R.id.loginId)).perform(typeText(&quot;a123456789&quot;)<br>      , ViewActions.closeSoftKeyboard())</pre><pre>    //type password<br>    onView(withId(R.id.password)).perform(typeText(&quot;1234&quot;)<br>      , ViewActions.closeSoftKeyboard())</pre><pre>    //click send button<br>    onView(withId(R.id.send)).perform(click())<br>    <br>    //register fail should alert<br>    onView(withText(&quot;Error&quot;))<br>        .inRoot(isDialog())<br>        .check(matches(isDisplayed()))<br>}</pre><p>Run the test and pass it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*HVx4VKiGy6I01yyqzhtbkA.gif" /></figure><p>Let’s refactor the code. The flowering codes show how to type a123456789 on loginId and type a111111111 on password.</p><pre>@Test<br>fun rightPassword_should_startActivity() {<br>    onView(withId(R.id.loginId)).perform(typeText(&quot;a123456789&quot;), ViewActions.closeSoftKeyboard())<br>    onView(withId(R.id.password)).perform(typeText(&quot;a111111111&quot;), ViewActions.closeSoftKeyboard())    ...<br>}</pre><p>Extract these two lines of codes to the inputRightRegisterData method. In this test case, we only need to know typing right id and password should start an Activity, the detail should be encapsulation.</p><pre>@Test<br>fun rightPassword_should_startActivity() {<br>    inputRightRegisterData()<br>    ...<br>}</pre><p>Same as wrong password tests case.</p><pre>@Test<br>fun wrongPassword_should_alert() {<br>    inputWrongRegisterData()<br>    ...<br>}</pre><p>Github:<br><a href="https://github.com/evanchen76/AndroidTDD_uitestsample">https://github.com/evanchen76/AndroidTDD_uitestsample</a></p><p>Reference:<br><a href="https://developer.android.com/training/testing/espresso">https://developer.android.com/training/testing/espresso</a></p><p>Next: Android TDD Part 10 —<strong> Robolectric</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-9-robolectric-1c90ae594f08">Android TDD Part 10— Robolectric</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54195cbf913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 8— Instrumented Tests]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-8-instrumented-tests-30b7d3c567e9?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b7d3c567e9</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 06:03:22 GMT</pubDate>
            <atom:updated>2020-07-30T02:20:09.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRU0SlWTlClVfRixlqmipA.png" /></figure><p>Mock every android framework may not be a good idea because we don’t know if the app can run on real devices. In the previous sample, we mock SharedPreference to let the test run on JVM.</p><p>This article, we’ll introduce another way: Separate to <strong>unit test</strong> and <strong>Instrumented test.</strong></p><p>First, create a SharedPreferenceManger which is to manage any process about SharedPreference.</p><h4>The two parts:</h4><p><strong>Local Unit test</strong>: To test Repository.saveUserId interact with ISharedPreferenceManager.</p><p><strong>Instrumented test</strong>: To test is SharedPreference saved data successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNeVESm8LQ80KwcpbLRIag.png" /></figure><p>Create a SharedPreferenceManager class that implements ISharedPreferenceManager interface. The method saveStringis used to save data by key. The method getString is used to get data by key.</p><pre>class SharedPreferenceManager(override val context: Context) <br>  : ISharedPreferenceManager {<br>    <br>    private val sharedPreferenceKey = &quot;USER_DATA&quot;<br>    var sharedPreference: SharedPreferences</pre><pre>    init {<br>        sharedPreference = <br>         context.getSharedPreferences(<br>          sharedPreferenceKey, Context.MODE_PRIVATE<br>         )<br>    }</pre><pre>    override fun saveString(key: String, value: String){<br>        sharedPreference.edit().putString(key, value).commit()<br>    }</pre><pre>    override fun getString(key: String): String {<br>        return sharedPreference.getString(key, &quot;&quot;)<br>    }<br>}</pre><p>In the Repository, use constructor injection to pass ISharedPreferenceManager instance. Now, we can call sharedPreferenceManager.saveString to save data.</p><pre>class Repository(<br>  val sharedPreferenceManager: ISharedPreferenceManager<br>  ) {</pre><pre>    fun saveUserId(id: String) {<br>        sharedPreferenceManager.saveString(&quot;USER_ID&quot;, id)<br>    }<br>}</pre><h3>Local Unit Test</h3><p>To verify if repository call mockSharedPreferenceManager.saveString()</p><pre>@Test<br>fun saveUserId() {<br>    val mockSharedPreferenceManager <br>      = mock(ISharedPreferenceManager::class.java)<br>    val userId = &quot;A1234567&quot;<br>    val preKey = &quot;USER_ID&quot;<br>    val repository = Repository(mockSharedPreferenceManager)<br>    <br>    //Act call repository.saveUserId()<br>    repository.saveUserId(userId)<br>    <br>    //Assert<br>    verify(mockSharedPreferenceManager).saveString(preKey, userId)<br>}</pre><h3>Instrumented Test</h3><p>In Instrumented Test, test if saved data successful.</p><pre>@RunWith(AndroidJUnit4::class)<br>class SharedPreferenceManagerTest {</pre><pre>    @Test<br>    fun <strong>useAppContext</strong>() {<br>        // Context of the app under test.<br>        val appContext = InstrumentationRegistry.getTargetContext()<br>        val key = &quot;User_Id&quot;<br>        val value = &quot;A123456789&quot;<br>        val sharedPreferenceManager: ISharedPreferenceManager <br>          = SharedPreferenceManager(appContext)</pre><pre>        sharedPreferenceManager.saveString(key, value)<br>        <br>        val valueFromSP = sharedPreferenceManager.getString(key)</pre><pre>        //get data fromSharedPreference and verify it.<br>        Assert.assertEquals(value, valueFromSP)<br>    }<br>}</pre><p>Run test, you can see an emulator or device is opened because it’s an Instrumented test. Although this kind of test takes most of the time, we still need an Instrumented test. Take both advance of unit test and instrumented test.</p><p>Github:<br><a href="https://github.com/evanchen76/AndroidTDD_InstrumentedTestSample">https://github.com/evanchen76/AndroidTDD_InstrumentedTestSample</a></p><p>Next: Android TDD Part 9 — <strong>UI Test: Espresso</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-9-ui-test-espresso-54195cbf913">Android TDD Part 9— UI Test: Espresso</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b7d3c567e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 7— Mock android framework]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-7-mock-android-framework-10340725398?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/10340725398</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 13:17:35 GMT</pubDate>
            <atom:updated>2020-07-25T06:04:35.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRU0SlWTlClVfRixlqmipA.png" /></figure><p>As we mentioned before, if tested object interacts with the Android framework, this test is an Instrumented test which means needs to be run on real devices or simulate. These kinds of tests will take the most time. This article, we&#39;ll introduce how to run tests as local tests by mocking the android framework.</p><p>From the previous registration sample, we want to save loginId after sign up success. SharedPreference is a good way to save data.</p><p>We already know it’s hard to test writing non UI logic in Activity. So, let&#39;s create a Repository to save data by using SharedPreference.</p><pre>class <strong>Repository</strong>(val context: Context) {<br>    // save UserId to SharePreference<br>    fun <strong>saveUserId</strong>(id: String) {<br>        val sharedPreference = <br>            context.getSharedPreferences(<br>              &quot;USER_DATA&quot;, Context.MODE_PRIVATE)<br><br>	sharedPreference.edit().putString(&quot;USER_ID&quot;, id).commit()<br>    }<br>}</pre><p>Call Repository(this).saveUserId(loginId) when sign up success in Activity.</p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>	super.onCreate(savedInstanceState)<br>	setContentView(R.layout.activity_main)<br><br>	send.setOnClickListener {<br>	    ...<br><br>  	    // sign up success, saveUserId<br>	    <strong>Repository(this).saveUserId(loginId)</strong><br>    }<br>}</pre><h3>Start testing</h3><p>Add a dependency to MockK library.</p><pre>dependencies {<br>    testImplementation &#39;io.mockk:mockk:1.9.3&#39;<br>}</pre><p><strong>Step:</strong></p><ol><li>Mock Context and SharePreference.</li><li>Use every returns to return mocking sharedPreference.</li><li>Call tested object repository.saveUserId(userId).</li><li>Use verify to check sharedPrefesEditor.putString() is pass right parameter.</li><li>Use verify to check sharedPrefsEditor.commit() is called.</li></ol><pre>@Test<br>fun saveUserId() {<br><br>    // <strong>1. Mock Context and SharePreference</strong><br>    val sharedPrefs = mockk&lt;SharedPreferences&gt;(relaxed = true)<br>    val sharedPrefsEditor = <br>        mockk&lt;SharedPreferences.Editor&gt;(relaxed = true)<br>    val context = mockk&lt;Context&gt;(relaxed = true)<br>	<br>    // <strong>2. Use every returns to return mocking sharedPreference.</strong><br>    every{context.getSharedPreferences(any(),any())}<br>      .returns(sharedPrefs)<br>    every{sharedPrefs.edit()}<br>      .returns(sharedPrefsEditor)<br>    every{sharedPrefsEditor.putString(any(), any())}<br>      .returns(sharedPrefsEditor)<br>	<br>    val userId = &quot;A1234567&quot;<br>    val preKey = &quot;USER_ID&quot;<br>	<br>    // <strong>3. Call tested object repository.saveUserId(userId)</strong><br>    val repository = Repository(context)<br>    repository.saveUserId(userId)<br>	<br>    // <strong>4. Use verify to check sharedPrefesEditor.putString() is pass right parameter.</strong></pre><pre>    verify{sharedPrefsEditor.putString(eq(preKey), eq(userId)) }<br>	<br>    // <strong>5. Use verify to check sharedPrefsEditor.commit() is called.</strong><br>    verify{sharedPrefsEditor.commit()}<br> }</pre><p>Click the green triangle to run the test. You&#39;ll see the testing duration is 20ms. Running a local test takes less time than the Instrument test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GV39vchC__FCy4ihAZAyg.png" /></figure><p><strong>Github:</strong><br><a href="https://github.com/evanchen76/AndroidTDD_MockSharedPreference">https://github.com/evanchen76/AndroidTDD_MockSharedPreference</a></p><p><strong>Next: </strong><br>Android TDD Part 8 — <strong>Instrumented Tests</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-8-instrumented-tests-30b7d3c567e9">Android TDD Part 8— Instrumented Tests</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10340725398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android TDD Part 6— First Android unit test]]></title>
            <link>https://medium.com/@evanchen7623/android-tdd-part-6-first-android-unit-test-8c363cd22044?source=rss-ffa369df87fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c363cd22044</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Evan Chen]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 15:42:18 GMT</pubDate>
            <atom:updated>2020-07-23T13:20:33.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRU0SlWTlClVfRixlqmipA.png" /></figure><p>Now, we are going to test on Android. There are three types of tests on Android:</p><ul><li>Local unit test</li><li>Instrumented unit test</li><li>UI test</li></ul><p><strong>Local unit test</strong></p><p>Local unit tests are running on your local machine which is the JVM environment. These tests don’t rely on the Android framework which means don’t need to install APK. The local unit test is fast. In the previous article, the tests we talk about are all local unit tests.</p><p><strong>Instrumented unit test</strong></p><p>The Instrumented unit test is also a unit test. The only difference between the local unit test is needed to run on an Android device or emulator. These tests need an Android framework, like context. The tests are slow because you need to install APK to the device or emulator.</p><p><strong>UI test</strong></p><p>UI test is used to verify users interacting like tapping buttons and typing words. This kind of test uses Espresso to test.</p><p>The local unit test is always preferred. It runs fast and stable. If the test depends on the Android framework, we can use Robolectric to mock the Android framework.</p><ul><li><strong>app/src/main/java</strong> - Android code, we call it production code.</li><li><strong>app/src/test/java</strong> - Local Unit tests, the test is run on JVM.</li><li><strong>app/src/androidTest/java</strong> - Instrumented unit tests and UI tests. the tests are run on emulators or devices.</li></ul><p>In “Testing Pyramid on Google I/O 2017”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SHO_Ymu9BK4oUoY9.png" /></figure><p>Reference: GoogleI/O 2017</p><p>The bottom of the pyramid is a unit test, this test should be fast. It runs on JVM. The second and third are run on devices and emulators. These two kinds of tests let you know that your app is running well on your device. When the error happened, it’s not easy to find the failure reason. And the test is slow because you need to install an APK to devices or emulators.</p><p>The UI tests are more important as unit tests. Any error will bring the user a poor experience. Google suggests 70% small tests, 20% medium tests, and 10% large tests.</p><p>The test pyramid is just to tell you that tests must have different levels, the benefits of each layer, the time spent is different. We can use it on limited resources and time.</p><p>The reason Android hard to test is because depending on the Android framework. We’ll try to use dependency injection, Mock, Stub, and MockK to solve these problems.</p><p>Let’s open Android Studio and write the first android unit test.</p><p>Project:</p><p><strong>app/src/test<br></strong>This directory contain the test that run on JVM.<br><strong>app/src/AndroidTest<br></strong>This directory contains the test on real or virtual devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z07WYt2SvDOfPlsf.png" /></figure><h3>First android unit test.</h3><p>When writing an app, the time you spend most is writing code in Activity. It’s easy to write too many codes in Activity including UI logic, business logic, and data. To write a good unit test, the first step is that moving your not UI logical code out of Activity.</p><h3>Extract non UI logic out of Activity.</h3><p>This is a typical registration function. You can type id and password then clicks the button to sign up.</p><ol><li>Id must at least 8 words.</li><li>Password must at least 8 words and the first letter should be alphabetized.</li><li>Click sign up. If the registration fails the validation check, the app should alert to show fail reason.</li><li>Click sign up. If register success, the app should redirect to the login success page.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*3tdBoVOLKFyYQWMLfbqIMw.png" /></figure><p>The following code shows how to check loginId format in Activity</p><pre>send.setOnClickListener {<br>    val loginId = loginId.text.toString()<br>    val pwd = password.text.toString()<br>    var isLoginIdOK = false<br>    //loginId at least 8 words and first letter should be alphabetized.<br>    if (loginId.length &gt;= 8) {<br>        if (loginId.toUpperCase().first() in &#39;A&#39;..&#39;Z&#39;) {<br>           isLoginIdOK = true<br>        }<br>    }<br>    ...<br>}</pre><p>It is hard to test writing logical codes in Activity.</p><h3>Let the code can be tested by extract method.</h3><p>The code of checking loginId is not related to UI. Let’s extract a method to do these things.</p><p>Extract checking codes to RegisterVerify.isLoginIdVerify()</p><pre>class RegisterVerify {<br>    fun isLoginIdVerify(loginId: String): Boolean {<br>        var isLoginIdOK = false</pre><pre>        //loginId at least 8 words and first letter should be alphabetized.<br>        if (loginId.length &gt;= 6) {<br>            if (loginId.toUpperCase().first() in &#39;A&#39;..&#39;Z&#39;) {<br>                isLoginIdOK = true<br>            }<br>        }<br>        return isLoginIdOK<br>    }<br>}</pre><p>Change code to call RegisterVerify().isLoginIdVerify(login) in Activity.</p><pre>var isLoginIdOK = RegisterVerify().isLoginIdVerify(loginId)</pre><h3>Start to write a test</h3><p>Since we extract loginId verification to RegisterVerify class, now we can write a test for RegisterVerify().isLoginIdVerify()</p><ol><li>Create a class RegisterVerifyTest in app/src/test</li><li>Add a test method loginVerifyTrue in class RegisterVerifyTest</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*oPVF9R5NRcfZRpW9.png" /></figure><pre>class RegisterVerifyTest {<br>    @Test<br>    fun loginVerifyTrue() {<br>        val registerVerify = RegisterVerify()<br>        //loginId is A123456 then verify result should be true<br>        assertTrue(registerVerify.isLoginIdVerify(&quot;A123456&quot;))<br>    }<br>    @Test<br>    fun loginVerifyFalse() {<br>        val registerVerify = RegisterVerify()<br>        //loginId is A12345 then verify result should be false<br>        assertFalse(registerVerify.isLoginIdVerify(&quot;A1234&quot;))<br>    }<br>}</pre><p>Click the green triangle to run test. You’ll see testing is pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*_jHUGQw0Zlq5I0uE.png" /></figure><p>It’s easy to write a test that functions like checking id, password, and email rules. These tests are also important and very easy to write wrong. But writing tests for them are very easy, just doing extract method.</p><p>Extract any codes that are not related to UI.</p><p>Not every situation can just use an extracting method to make code testable. The more advanced way we will introduce later. Generally, we don’t refactor code before writing a test for it. In this sample, you can write a UI test to protect your code before you refactor it.</p><p>Github:<br><a href="https://github.com/evanchen76/AndroidTDD_AndroidUnitTestSample">https://github.com/evanchen76/AndroidTDD_AndroidUnitTestSample</a></p><p><strong>Tip:</strong></p><p>Extract method:<br>Command + Option + M ( Ctrl + Alt + M)</p><p>Next: Android TDD Part 7 — <strong>Mock android framework</strong></p><p><a href="https://medium.com/@evanchen7623/android-tdd-part-7-mock-android-framework-10340725398">Android TDD Part 7— Mock android framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c363cd22044" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>