<?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 Oleg Osipenko on Medium]]></title>
        <description><![CDATA[Stories by Oleg Osipenko on Medium]]></description>
        <link>https://medium.com/@olegosipenko?source=rss-d0729c3789ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K9k-v5lZKDK_1L9eOBXkAQ.jpeg</url>
            <title>Stories by Oleg Osipenko on Medium</title>
            <link>https://medium.com/@olegosipenko?source=rss-d0729c3789ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 06:27:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olegosipenko/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[Kotlin: when statement, when expression… oh my! or How we created our custom Detekt rule]]></title>
            <link>https://proandroiddev.com/kotlin-when-statement-when-expression-oh-my-or-how-we-created-our-custom-detekt-rule-6f27e80bedaf?source=rss-d0729c3789ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f27e80bedaf</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-apps-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[detekt]]></category>
            <dc:creator><![CDATA[Oleg Osipenko]]></dc:creator>
            <pubDate>Thu, 19 Sep 2019 10:58:54 GMT</pubDate>
            <atom:updated>2023-05-11T15:03:59.429Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Important update: as of April 2021 there is an official detekt rule for checking when cases —</strong><a href="https://github.com/detekt/detekt/blob/main/detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/MissingWhenCase.kt"><strong> MissingWhenCase</strong></a><strong>. Please use it</strong></p><p>Back in 2015 when I only started trying Kotlin (many thanks to <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a> for his <a href="https://docs.google.com/document/d/1ReS3ep-hjxWA8kZi0YqDbEhCqTt29hG8P44aA9W0DM8/">thorough investigation</a>) and then later, when Kotlin 1.0 was released and year after announced by Google as a priority language for development on Android, in the long list of shiny Kotlin features, presented by the articles and blog posts related to the new language, sealed classes were one of the most interesting for me. They were advertised as <em>better enums</em>, <em>enums with super power </em>etc. And one of the answers to the question why it’s better enum, was the ability of compiler to complain if you forgot to handle one of the cases while using when on sealed class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6aafef2bf40b6d0554edcaabd588563/href">https://medium.com/media/b6aafef2bf40b6d0554edcaabd588563/href</a></iframe><p>If you try to compile this code, you will receive the error: &#39;when&#39; expression must be exhaustive. Add remaining branches or &#39;else&#39; branch.</p><p>I remembered that piece of information and, until recently, completely believed into it. Now you could imagine, how I was surprised when I found that it’s not true. Or being precise, not always true.</p><h3>When expression and when statement</h3><p>So, recently we started a new project here in AUTO1 and of course Kotlin was our choice. And we decided to use sealed classes to represent the set of states of our screens. Something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/692f10865963e7c5d44d2f36d76ce5f0/href">https://medium.com/media/692f10865963e7c5d44d2f36d76ce5f0/href</a></iframe><p>Inside the fragment I created render(viewState: EmailLoginViewState) function and started implementing it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1d7dada6bb61b103e95c9597ba1e29/href">https://medium.com/media/1f1d7dada6bb61b103e95c9597ba1e29/href</a></iframe><p>Surprisingly, I didn’t get any compiler warnings at this point, although I knew that I haven’t covered other cases of this sealed class. How could it be possible? So I decided to start my investigation from reading documentation.</p><figure><img alt="It’s very useful to read documentation…" src="https://cdn-images-1.medium.com/max/594/1*dPfr-xoD11cLLvdctALyhA.png" /><figcaption>It’s very useful to read documentation…</figcaption></figure><p>So, that’s what I found in <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">Kotlin sealed classes documentation</a>:</p><blockquote>The key benefit of using sealed classes comes into play when you use them in a <a href="https://kotlinlang.org/docs/reference/control-flow.html#when-expression">when expression</a>. If it&#39;s possible to verify that the statement covers all cases, you don&#39;t need to add an else clause to the statement. However,<strong> this works only if you use </strong><strong>when as an expression (using the result) and not as a statement.</strong></blockquote><p>In my case I was using when as a <strong>statement</strong>, I didn’t use the result of the when anywhere in my code, that’s why it wasn’t <strong>expression</strong>. And what’s why compiler wasn’t complaining about not covered cases in my sealed class.</p><h3>Make when expression out of statement</h3><p>The recipe was obvious: I need to use the result of when expression in order to enable compiler warnings. But how to make it in the most idiomatic way?</p><p>We considered a number of options:</p><ol><li>Assign the result of the when expression to some variable:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4721c2c09e909d5261f412ba9ce35644/href">https://medium.com/media/4721c2c09e909d5261f412ba9ce35644/href</a></iframe><p>2. Return the result of the when exression out of the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f92e10147f82a22b68e0bd1f581b7aa9/href">https://medium.com/media/f92e10147f82a22b68e0bd1f581b7aa9/href</a></iframe><p>3. Add empty let block after when expression:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c078f4b79227df1a75f1d7c17bfa4db/href">https://medium.com/media/0c078f4b79227df1a75f1d7c17bfa4db/href</a></iframe><p>All these methods transform when <em>statement</em> to when <em>expression</em>, enabling compiler warnings. But they all are not perfect: they are not readable; they bring some layer of ambiguity into our code; they hide the knowledge since the purpose of extra let block or storing result of when expression in some variable was unclear.</p><p>There’s no perfect solution to this problem. We decided to follow <a href="https://proandroiddev.com/til-when-is-when-exhaustive-31d69f630a8b">one of the advices</a> and to create an extension property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e825514e25147cd3bfb40ef9c6dbac9/href">https://medium.com/media/6e825514e25147cd3bfb40ef9c6dbac9/href</a></iframe><p>It works similar to empty let block, but it’s more readable — it’s name is self-explanatory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bfd69da64d6c878e5bf93c33e9a52ca/href">https://medium.com/media/6bfd69da64d6c878e5bf93c33e9a52ca/href</a></iframe><p>Now compiler checks our when expressions and that could have been the happy end of our story…</p><p>So far so good as now we have compiler warnings. But still part of the problem is present — that is a hidden knowledge: new team member having no idea about exhaustive property would never use it.</p><p>Of course, we can add it to the documentation of our project, we can make this topic part of the on-boarding process… But still there’s left some place for human factor. Maybe it’s better to delegate this to machine? So, let’s do it!</p><p>We are using <a href="https://arturbosch.github.io/detekt/">Detekt</a> for static analysis of our Kotlin code so we decided to create a custom Detekt rule to check if when block was used in pair with exhaustive property.</p><p>For those of you who haven’t had experience with Detekt I could recommend great intro into Detekt by <a href="https://medium.com/u/9057ae5f9de4">Mohit Sarveiya</a> (slides <a href="https://speakerdeck.com/heyitsmohit/static-code-analysis-with-kotlin">here</a>):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLT6m5_LO2DQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLT6m5_LO2DQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLT6m5_LO2DQ%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/cab98fc1635a94c715150ec981f507fe/href">https://medium.com/media/cab98fc1635a94c715150ec981f507fe/href</a></iframe><p>The <a href="https://medium.com/@vanniktech/writing-your-first-detekt-rule-ee940e56428d">article</a> of <a href="https://medium.com/u/c9d576fec3d5">Niklas Baudy</a> was also kind of inspiration and guide for us.</p><h3>PSI</h3><p>Detekt uses a Kotlin PSI to perform checks. PSI states for Program Structure Interface, and each JetBrains IDE uses it for code completion, syntax highlighting etc. Every program could be represented as a hierarchy of PSI elements. For example, this simple program:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3430d618922bde9549234e68f5a29c3c/href">https://medium.com/media/3430d618922bde9549234e68f5a29c3c/href</a></iframe><p>will give us the following PSI tree (very simplified):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*78K4vwEjIiFfZqOsQ6imeg.png" /></figure><p>This tree helps Detekt and other static analysis tools to assess any element of the code. And we will use it to check our when directives. And from the PSI point of view there could be 4 possible situations:</p><ol><li>If we are assigning the result of our when expression to some variable it is considered to be a <strong>KtProperty</strong>:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4721c2c09e909d5261f412ba9ce35644/href">https://medium.com/media/4721c2c09e909d5261f412ba9ce35644/href</a></iframe><p>2. If we are returning the result of our when expression from the function it’s the <strong>KtBlockExpression</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f92e10147f82a22b68e0bd1f581b7aa9/href">https://medium.com/media/f92e10147f82a22b68e0bd1f581b7aa9/href</a></iframe><p>3. If we are chaining some extension after our when block, for PSI it becomes <strong>KtDotQualifiedExpression:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c697ba0ebd15fa96c01b5c706532db2a/href">https://medium.com/media/c697ba0ebd15fa96c01b5c706532db2a/href</a></iframe><p>4. And our initial when statement (if we are not using the result) in terms of PSI is <strong>KtWhenExpression:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1d7dada6bb61b103e95c9597ba1e29/href">https://medium.com/media/1f1d7dada6bb61b103e95c9597ba1e29/href</a></iframe><p>Having this, we can formulate what our check should do: it should visit content of our Kotlin classes and look for instances of KtWhenExpession and yell at us if so.</p><h3>Rule implementation</h3><p>Let’s start with creating a new module in our project and name it detekt-rules. And we need to add to our module’s build.gradle detekt-api artifact as a dependency:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9022e7cd57d5b9b754a323984945f227/href">https://medium.com/media/9022e7cd57d5b9b754a323984945f227/href</a></iframe><p>Now we can create class for our Detekt rule. Rule class describes the issue and also contains the logic of detecting it. Let’s call our class NonExhaustiveWhen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de8d44be463a1b00e5bb019d099550f1/href">https://medium.com/media/de8d44be463a1b00e5bb019d099550f1/href</a></iframe><p>We are passing number of parameters to the constructor of the superclass:</p><ul><li>We need to specify severity of our issue. Here we chose Defect.</li><li>We need to provide a description of the issue</li><li>We need to specify time estimate to fix the issue, so that Detekt could calculate total amount of time required to fix all issues in the codebase. Since this fix only requires adding one method call, we estimated it to minimum amount of FIVE_MINS.</li></ul><p>We are extending here Rule class. Its constructor parameters, as we’ve already seen, describe the issue. But in order to check our code for the issue Rule class also inherits from KtVisitor class . It provides us with a huge API: more than one hundred methods — each one for visiting specific PSI element, such as visitFile(file: PsiFile?), visitClassBody(classBody: KtClassBody), visitArgument(argument: KtValueArgument) etc. And we can override any of these methods to add our checks. And we will override visitNamedFunction() method to add our check. For each KtNamedFunction that is detected while traversing the PSI, this method will be called exactly once:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bd64b30028ca211bd85060c5ef833e2/href">https://medium.com/media/5bd64b30028ca211bd85060c5ef833e2/href</a></iframe><p>Here we are filtering children of the KtNamedFunction looking out for instances of KtWhenExpession. If it’s empty, everything is fine. Otherwise, we use report method to signal our Finding. We are calling report method and passing some message, providing some hints on how to fix this issue.</p><p>Our class now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdedb62eb364967278190a8db9a22f52/href">https://medium.com/media/bdedb62eb364967278190a8db9a22f52/href</a></iframe><p><strong>UPD: </strong>As pointed by <a href="https://medium.com/u/89f97b448af0">Xavier Rubio Jansana</a> visitNamedFunction visits only named function, so code of anonymous lambdas wouldn’t be checked. To deal with lambdas we need to implement visitLambdaExpression function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a14e44e8ab0b163a2e016bda8a62c254/href">https://medium.com/media/a14e44e8ab0b163a2e016bda8a62c254/href</a></iframe><h3>Testing our rule</h3><p>In order to believe in our rule veracity let’s write some unit test for it. To test rules we need add detekt-test artifact in our module’s build.gradle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6efb28f048c21ebead6272ee46e16bd5/href">https://medium.com/media/6efb28f048c21ebead6272ee46e16bd5/href</a></iframe><p>There’s an extension function lint() for BaseRule class, which executes the check and we will use it for our tests.</p><p>We need to create some inputs for our tests. For the sake of simplicity let’s create simple string values for our test inputs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5588b4d3badc35f816d9106fca7801bf/href">https://medium.com/media/5588b4d3badc35f816d9106fca7801bf/href</a></iframe><p>Now, we can test our rule. First, let’s check non-compliant input, representing when statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1957ff3efa9d4fc7d625f91925bd3083/href">https://medium.com/media/1957ff3efa9d4fc7d625f91925bd3083/href</a></iframe><p>Then, let’s test compliant inputs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c7708d96e06d75c8a04369e1ecd373/href">https://medium.com/media/c1c7708d96e06d75c8a04369e1ecd373/href</a></iframe><p>Since we have 3 different inputs, which should provide us the same result, I am using <a href="https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests">JUnit 5 </a><a href="https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests">ParameterizedTest</a> feature to run the same test with different inputs. I use MethodSource as inputs provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c98b4645d5ee214f6b6a9334984deaf3/href">https://medium.com/media/c98b4645d5ee214f6b6a9334984deaf3/href</a></iframe><p>Thanks for JUnit 5 annotations ParameterizedTest and DisplayName we can get meaningful outputs in the test results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*wd18hr4aRA6lchTGwXzgKQ.png" /></figure><h3>RulesetProvider</h3><p>Now we have our rule and tests running, our rule is ready to check kotlin files. In order to make our check accessible by Detekt we need to create instance of RuleSetProvider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8a6c1ecfb49d7cff29a8d9d0ecd996a/href">https://medium.com/media/a8a6c1ecfb49d7cff29a8d9d0ecd996a/href</a></iframe><p>RulesetProvider is responsible for storing the registry of all the rules, accessible by Detekt. Since it’s just a hook for Detekt to look for rules there’s nothing special happens here. We just need to provide unique id for our ruleset and include our custom check classes into the list of rules.</p><p>Other important step here is to notify Detekt about our ruleset provider. For that we need to create a file with the name io.gitlab.arturbosch.detekt.api.RuleSetProvider and place it in the directory src/main/resources/META-INF/servises. The content of this file should be the fully qualified class name of our custom ruleset provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/922b863bfbe279eeaa86edfc6fd49b19/href">https://medium.com/media/922b863bfbe279eeaa86edfc6fd49b19/href</a></iframe><h3>Enabling our check</h3><p>By default Detekt has a number of built-in rulesets. Before enabling our ruleset we need to add dependency of our detekt-rules module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de6d78a7ce82c25111b92ff40cde408d/href">https://medium.com/media/de6d78a7ce82c25111b92ff40cde408d/href</a></iframe><p>Then we should include our ruleset and rule into Detekt configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc2901f9fe4f71d4a40a85ebef3390c/href">https://medium.com/media/4cc2901f9fe4f71d4a40a85ebef3390c/href</a></iframe><p>Here on top level we list our ruleset name, the next level is there we list individual rules from this ruleset. Each of them we can turn on or off.</p><h3>Tying things together</h3><p>Now let’s try run Detekt on our code and you will see the output like this:</p><pre>./gradlew detekt</pre><pre>&gt; Task :app:detekt FAILED<br>.....</pre><pre>5 kotlin files were analyzed.<br>Ruleset: detekt-rules - 5min debt<br>   NonExhaustiveWhen - [render] at /Users/oleg.osipenko/StudioProjects/KoinTestApp/app/src/main/java/com/github/olegosipenko/kointestsample/EmailLoginFragment.kt:30:3</pre><pre>Overall debt: 5min</pre><pre>Complexity Report:<br>        - 102 lines of code (loc)<br>        - 80 source lines of code (sloc)<br>        - 40 logical lines of code (lloc)<br>        - 1 comment lines of code (cloc)<br>        - 8 McCabe complexity (mcc)<br>        - 1 number of total code smells<br>        - 1 % comment source ratio<br>        - 200 mcc per 1000 lloc<br>        - 25 code smells per 1000 lloc</pre><pre>Project Statistics:<br>        - number of properties: 4<br>        - number of functions: 7<br>        - number of classes: 5<br>        - number of packages: 1<br>        - number of kt files: 5</pre><pre>detekt finished in 1200 ms.<br>Successfully generated HTML report at /Users/oleg.osipenko/StudioProjects/KoinTestApp/app/build/reports/detekt/detekt.html<br>Build failed with 1 weighted issues (threshold defined was 0).<br>io.gitlab.arturbosch.detekt.cli.BuildFailure: Build failed with 1 weighted issues (threshold defined was 0).</pre><p>Learning a new programming language is always exciting and could be much more useful if combined with reading documentation. That could help to better understand the subtle nuances of technology you are trying to master. And if you want to establish some practice of using some language feature, it’s better to offload this responsibility to static analysis tool, such as Detekt.</p><p>Detekt offers great API to create custom rules and it’s not very difficult to write and add your rules. This will improve your code and make your life easier.</p><p>You can check the source code for the sample <a href="https://github.com/olegosipenko/SamplesApp">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f27e80bedaf" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-when-statement-when-expression-oh-my-or-how-we-created-our-custom-detekt-rule-6f27e80bedaf">Kotlin: when statement, when expression… oh my! or How we created our custom Detekt rule</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 your isolated Fragments  with Koin]]></title>
            <link>https://proandroiddev.com/testing-your-isolated-fragments-with-koin-9d9d39f7b17e?source=rss-d0729c3789ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9d39f7b17e</guid>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[mockk]]></category>
            <category><![CDATA[kakao]]></category>
            <dc:creator><![CDATA[Oleg Osipenko]]></dc:creator>
            <pubDate>Sat, 17 Aug 2019 12:33:35 GMT</pubDate>
            <atom:updated>2019-09-19T11:53:01.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing your isolated Fragments with Koin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*v7s-4lFtOXNvOODrQRPGgw.png" /></figure><p>UI-tests are a necessary part of our development routine in <a href="https://www.auto1-group.com/">AUTO1</a>. Although that wasn’t the case a while ago. One of the issues, which was blocking developers from writing and running UI-tests, was the need to set up UI-tests. Of course, to test the screen in isolation you need to have some architecture, employ the SOLID principles, especially Dependency inversion. With proper architecture it’s easy to substitute dependencies inside screen under the test with fakes or mocks. But even with good architecture you need to provide these mock implementations. And it’s not always obvious how to make your DI framework to provide mocks for tests.</p><p>Recently we started a brand new project from scratch. And we decided to give <a href="https://insert-koin.io/">Koin</a> a try. Why Koin and not Dagger? — Just because Koin offers concise and minimalistic syntax and it uses Kotlin. Also, important for us was the question of code generation. Although Google announced that in new versions of Android Gradle plug-in they made kapt incremental, we still didn’t want to add this extra burden to our build process. Simultaneously Koin 2.0 was announced at the same time. That’s how we found ourselves facing question: how to provide mock dependencies to our UI-tests?</p><p><strong>Let’s start with fragment…</strong><br>Inside our fragments we inject number of dependencies, typically they include viewmodels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd7a192ccc5041bed4dd791ea954dfe/href">https://medium.com/media/1cd7a192ccc5041bed4dd791ea954dfe/href</a></iframe><p>That’s exactly what we want to substitute with mocks. To do so we need a custom Application class, which will start Koin with our test module, not the real one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78071cc097cd99ed4615d648d883f9e3/href">https://medium.com/media/78071cc097cd99ed4615d648d883f9e3/href</a></iframe><p>We start our Koin instance inside onCreate() method, and we pass emptyList()of modules. We also have a method injectModule() which accepts our test module. Since we already started our application, we are using method loadKoinModules()to add this test module to the graph.</p><p><strong>How to run custom application</strong></p><p>But we need to somehow start our test application class. We cannot use AndroidManifest inside androidTest folder, because manifest merger will ignore it if we set our test application inside Manifest like this: <br>&lt;application name=&quot;.KoinTestApp&quot;&gt;. So we could use a custom test runner for that purpose. AndroidJUnitRunner class has a newApplication() method. And we can pass our test application name there, making our test runner to start our test application instead of a real one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b80ea64b80e066c9f6b235af9bbac3/href">https://medium.com/media/c5b80ea64b80e066c9f6b235af9bbac3/href</a></iframe><p>Then we need to change our build.gradle inside our app module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18262d9826977c9e2ea7c04489464aa2/href">https://medium.com/media/18262d9826977c9e2ea7c04489464aa2/href</a></iframe><p>And don’t forget to disable animations for UI-tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1323d09f10f697f441d318705b66548/href">https://medium.com/media/c1323d09f10f697f441d318705b66548/href</a></iframe><p><strong>Test rule for fragments</strong></p><p>We are almost done. We only need to write our test and provide our test module to it. We are using our custom fragment test rule, which provides a couple of methods for submitting your fragment and mock test module. But you could use the same approach for activities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89735955d6fbb890dd91c72c7d5046d4/href">https://medium.com/media/89735955d6fbb890dd91c72c7d5046d4/href</a></iframe><p>I am using default Android FragmentActivity to host fragment under test. So we need to mention this activity in the manifest. For that purpose I created instance of AndroidManifest inside debug variant in my app module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c55eb992fa9d9fbcc9701ad07afbe30/href">https://medium.com/media/2c55eb992fa9d9fbcc9701ad07afbe30/href</a></iframe><p><strong>Test itself</strong></p><p>Finally, our test class could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d782559d978be9c83064d1db8800cffe/href">https://medium.com/media/d782559d978be9c83064d1db8800cffe/href</a></iframe><p>Here we are using <a href="http://github.com/agoda-com/Kakao/">Kakao</a>, it’s a nice tool to simplify working with Espresso tests. It provides implementation of <a href="https://martinfowler.com/bliki/PageObject.html">Page Object pattern</a> and allows you to abstract interactions with your UI behind the abstract <a href="https://github.com/agoda-com/Kakao/blob/master/kakao/src/main/kotlin/com/agoda/kakao/screen/Screen.kt">Screen</a> objects. Using Kakao you can improve maintainability of your tests, so if you are not using it yet, give it a try. Also we are using <a href="https://mockk.io/">Mockk</a> for mocking, which uses all the power Kotlin gives us.</p><p>That’s how with Koin, Kakao and Mockk you could easily test your fragments in isolation, making your life easier.</p><p>You can check the source code for the sample <a href="https://github.com/olegosipenko/SamplesApp">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9d39f7b17e" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/testing-your-isolated-fragments-with-koin-9d9d39f7b17e">Testing your isolated Fragments  with Koin</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>
    </channel>
</rss>