<?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 Adam Speakman on Medium]]></title>
        <description><![CDATA[Stories by Adam Speakman on Medium]]></description>
        <link>https://medium.com/@adamspeakman?source=rss-5bbe871a2843------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o-cnT4xGbaqo45QlX9i0Kw.jpeg</url>
            <title>Stories by Adam Speakman on Medium</title>
            <link>https://medium.com/@adamspeakman?source=rss-5bbe871a2843------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:35:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adamspeakman/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[Mockito UnfinishedStubbingException in tests]]></title>
            <link>https://medium.com/@adamspeakman/mockito-unfinishedstubbingexception-in-tests-3d622532d491?source=rss-5bbe871a2843------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d622532d491</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Adam Speakman]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-04-08T22:02:06.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3Q-atTk4pg4R5AaqmGUlQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1td5Iq5IvNc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maximilian Weisbecker</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Ever wonder why Mockito will occasionally give you an UnfinishedStubbingException even though you <em>clearly</em> finished the stubbing?</p><p>For example, the following code will fail at runtime (mockChannel has been set up earlier, whenever is an alias of Mockito#when):</p><pre>whenever(mockChannelNameProvider.nameForChannel(mockChannel))<br>    .thenReturn(mockChannel.id())</pre><p>With an exception like this:</p><pre>org.mockito.exceptions.misusing.UnfinishedStubbingException: <br>Unfinished stubbing detected here:<br>-&gt; at ExampleFailingTestKotlin.setupChannelName(ExampleInterfacesTest.kt:30)</pre><pre>E.g. thenReturn() may be missing.<br>Examples of correct stubbing:<br>    when(mock.isOk()).thenReturn(true);<br>    when(mock.isOk()).thenThrow(exception);<br>    doThrow(exception).when(mock).someVoidMethod();<br>Hints:<br> 1. missing thenReturn()<br> 2. you are trying to stub a final method, which is not supported<br> 3: you are stubbing the behaviour of another mock inside before &#39;thenReturn&#39; instruction is completed</pre><p>This is a very good exception message. It gives you some common examples of what you might have done wrong, and how to fix them. However, our code doesn’t match any of the examples.</p><p>If we look at the generated Java for this (Tools &gt; Kotlin &gt; Show Kotlin Bytecode &gt; Decompile), it <em>still</em> looks like it should work - we definitely finish the stubbing:</p><pre>Channel var10001 = this.mockChannel;<br>if (var10001 == null) {<br>  Intrinsics.throwUninitializedPropertyAccessException(&quot;...&quot;);<br>}</pre><pre>OngoingStubbing var2 = Mockito.when(var1.nameForChannel(var10001));<br>var10001 = this.mockChannel;<br>if (var10001 == null) {<br>  Intrinsics.throwUninitializedPropertyAccessException(&quot;...&quot;);<br>}</pre><pre>var2.thenReturn(var10001.id());</pre><p>So why do we get an UnfinishedStubbingException? <em>Because we’re accessing a mock before we finish the stubbing.</em></p><p>The failure happens on this line from the decompiled Kotlin bytecode:</p><pre>var2.thenReturn(var10001.id());</pre><p>Let’s make this a little clearer by using descriptive names:</p><pre>ongoingStubbing.thenReturn(mockChannel.id());</pre><p>You can break this apart a little further:</p><pre>String id = mockChannel.id();<br>ongoingStubbing.thenReturn(id);</pre><p>So we have a reference to an OngoingStubbing. Internally, Mockito statically maintains a reference to a MockingProgress. When we access the mock (mockChannel.id()) after we’ve already started the stubbing, Mockito goes off to the MockingProgress and <a href="https://github.com/mockito/mockito/blob/49e07acc30fb486a8af773977e461cf4d1c876ec/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java#L64">calls through to a </a><a href="https://github.com/mockito/mockito/blob/49e07acc30fb486a8af773977e461cf4d1c876ec/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java#L64">validateState() method</a>, which does this:</p><pre>public void validateState() {<br>  validateMostStuff();</pre><pre> //validate stubbing:<br>  if (stubbingInProgress != null) {<br>      Location temp = stubbingInProgress;<br>      stubbingInProgress = null;<br>      throw unfinishedStubbing(temp);<br>  }<br>}</pre><p>Because a stubbing is still in progress, we get an UnfinishedStubbingException. 💥</p><p>We can fix this by pulling the variable out of the mock on the line before we start the stubbing:</p><pre>val channelName = mockChannel.id()<br>whenever(mockChannelNameProvider.nameForChannel(mockChannel))<br>    .thenReturn(channelName)</pre><p>Of course, make sure to comment <em>why</em> you’re doing this for the next developer who comes along and tries to simplify this by inlining the variable.</p><p>Now that we see why it’s happening, it makes sense. Accessing a mock while setting up a different one is a bit of a code smell — they should probably be accessing some constant value. One of the best ways to prevent this situation is to use fakes not mocks for your models. Obviously, this isn’t always easy though — you might have legacy concerns that prevent this or you might need to make sure that you return the same thing from two different interfaces.</p><p>This can be a very confusing error to debug, especially when it’s deep in some utility or setup method (where it might not even be obvious that you’re accessing something on a mock), or when you’re in the process of converting some legacy code. Next time you encounter it, consider whether you can do some refactoring to make it harder to hit.</p><p>You can find the <a href="https://github.com/adamsp/mockito-tests">source code for this post here</a>.</p><p><em>Originally published at </em><a href="http://speakman.net.nz/blog/2019/04/07/mockito-unfinishedstubbingexception-in-tests/"><em>speakman.net.nz</em></a><em> on April 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d622532d491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronously loading data using Google’s Paging Library]]></title>
            <link>https://medium.com/@adamspeakman/asynchronously-loading-data-using-googles-paging-library-d87fa411fa4?source=rss-5bbe871a2843------2</link>
            <guid isPermaLink="false">https://medium.com/p/d87fa411fa4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-support-library]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Adam Speakman]]></dc:creator>
            <pubDate>Mon, 09 Oct 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-11T00:24:38.493Z</atom:updated>
            <content:encoded><![CDATA[<p>The recently released <a href="https://developer.android.com/topic/libraries/architecture/paging.html">Paging Library</a> from Google gives you an easy way to page data into memory off of the main thread. If you want to use it with <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a>, then the built-in support makes it trivial. However, if you’d like to page data that exists elsewhere — from the network or disk, for example — then you have to do a little extra work.</p><p>Here I demonstrate how to take existing code that loads a list of screenshots from disk and convert it to load asynchronously using the Paging Library. This example could easily be adapted for network calls.</p><p>Throughout this post we’ll be using a Screenshot class defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fcbc46b69012dae52192b9e613a48b/href">https://medium.com/media/79fcbc46b69012dae52192b9e613a48b/href</a></iframe><p>You will also need to import the library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca842cbaa1261ff0650b248e521c317/href">https://medium.com/media/4ca842cbaa1261ff0650b248e521c317/href</a></iframe><h3>Existing code</h3><p>When the app launches, it shows the user a list of images from a directory they supply during setup. My existing code was a simple repository that loaded <em>all</em> screenshots (as a Uri and width/height values) from this directory via Android’s storage access framework. The code was similar to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b49530f4d3a2b4af28056bf7a5843da9/href">https://medium.com/media/b49530f4d3a2b4af28056bf7a5843da9/href</a></iframe><p>As you can see, we have to go to disk to get information about every screenshot. This is expensive! On my test device I’ve only got around 100 screenshots — on a device that’s been around longer a user could have many hundreds or thousands of screenshots in this folder. Rather than loading these all up front, I need to load these asynchronously. In addition, since these are in a list there’s a high likelihood that the items further down the list won’t even be needed. The Paging Library helps with these problems.</p><h3>Paging Library Fundamentals</h3><p>The Paging Library has 3 different “levels” that build on top of each other.</p><p>At the base, we have a kind of <a href="https://developer.android.com/reference/android/arch/paging/DataSource.html">DataSource</a>. This can be either “keyed” (such that you need to know about the item at index N-1 in order to know about the item at index N — like a linked list), or “tiled” (such that you can access elements at arbitrary indices — like an array list).</p><p>Above that, we have a <a href="https://developer.android.com/reference/android/arch/paging/PagedList.html">PagedList</a>, which as its name suggests, is a list that pages its data in from a DataSource.</p><p>Finally we have the <a href="https://developer.android.com/reference/android/arch/paging/PagedListAdapter.html">PagedListAdapter</a>, which is a RecyclerView.Adapter that neatly wraps a PagedList, calling the correct notifyItem… methods for you as your data changes (when you call setList with a new PagedList) or loads in. This is fairly standard RecyclerView boilerplate. If you need some custom behaviour, you can duplicate its functionality — it’s just a handy wrapper around the <a href="https://developer.android.com/reference/android/arch/paging/PagedListAdapterHelper.html">PagedListAdapterHelper</a>.</p><h3>Constructing a Data Source</h3><p>A DataSource is reasonably simple. For a list like this, we implement a TiledDataSource, doing the expensive disk IO in the loadRange method. The PagedList will call this from a background thread when it is time to load a new page of data.</p><p>Note that it does <em>not</em> clamp ranges for you — so if you have 10 items and a page size of 6, your second page will be startPosition = 6 and count = 6 — which will give you an IndexOutOfBoundsException. Make sure to clamp your inputs as I do here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f4713e9dfa571168a8a64d8018e7b3b/href">https://medium.com/media/0f4713e9dfa571168a8a64d8018e7b3b/href</a></iframe><p>Note here the DataSource&lt;Int, Screenshot&gt; — those types are&lt;Key, Value&gt;. Because we’re using a TiledDataSource our key is already defined to be an Int. Later, when we’re creating a PagedList, the builder assumes that a TiledDataSource uses an Int key — which makes sense, as we can access any element in this source by index.</p><h3>Building a Paged List</h3><p>For my use-case, 8 elements on a ‘page’ was sufficient. I’m showing images in a 2-column list; most of the elements are around half the window height. You’ll need to decide what works well for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e3e4ec7fe1f5febe386328ba4257870/href">https://medium.com/media/9e3e4ec7fe1f5febe386328ba4257870/href</a></iframe><p>Note that here we use the default prefetch distance of pageSize — that is, as soon as the first item in a given page of data is requested, the next page will begin loading. Depending on your data, you may want this to be smaller or larger.</p><p>We also enable placeholders (this is actually enabled by default). Since we know exactly how many elements are going to be in our list (we have Uris for every screenshot, even if we don’t have any details about that screenshot yet) we can use null placeholders while the images load — helping avoid weird scrollbars. Our onBindViewHolder has to deal with these null values later. I’d recommend <a href="https://developer.android.com/reference/android/arch/paging/PagedList.html">reading the </a><a href="https://developer.android.com/reference/android/arch/paging/PagedList.html">PagedList docs</a> — they go into more detail on placeholders.</p><p>You need to supply two <a href="https://developer.android.com/reference/java/util/concurrent/Executor.html">Executor</a>s — one for posting back to the main thread, and another for background work. In this example we create a main thread Handler and post events to it directly, but our disk IO Executor is injected from elsewhere.</p><p>Finally, this code has one subtle gotcha — the first two pages will be loaded immediately on whatever thread the final build() is called from! From the docs:</p><blockquote>Creating a PagedList loads data from the DataSource immediately, and should for this reason be done on a background thread. The constructed PagedList may then be passed to and used on the UI thread. This is done to prevent passing a list with no loaded content to the UI thread, which should generally not be presented to the user.</blockquote><p>In this case, we’ll be going to disk 16 times (8 for the first page, and then another 8 as the second page is pre-fetched). I address this later when I wire everything together.</p><p>You can also specify an initial key to load around — here we don’t specify one, and hence default to 0 (i.e. the first item in the list). If your list starts with an offset you can start your loading around that location — this works for both TiledDataSource and KeyedDataSource.</p><h3>Adding the Adapter</h3><p>The simplest part of all. We just extend PagedListAdapter, supplying a simple DiffCallback for comparing Screenshot objects, and implement onBindViewHolder and onCreateViewHolder like normal.</p><p>Note if you have custom logic (such as a custom BindingAdapter — not shown here) you need to be aware that the object returned from getItem <em>can be</em> null — these are the placeholders we enabled earlier, and will be null while the data at that index loads. If your page sizes are appropriate, receiving a null object will be rare, but you <em>must</em> handle it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05a9743c87126957b04defb6c19c62a7/href">https://medium.com/media/05a9743c87126957b04defb6c19c62a7/href</a></iframe><h3>Wiring it all up</h3><p>Now we have all the pieces we can put them together. Note that I supply an async callback for loading the screenshots — the ScreenshotLoader uses the disk executor we supply in the constructor to do the actual building (since this loads the first page or more, as mentioned above!). We then set the result on our list once that load has finished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da54f7b64e5b4ae122fe19bf9849a6ff/href">https://medium.com/media/da54f7b64e5b4ae122fe19bf9849a6ff/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cd9f4152d07a1c75938d8204bf0d668/href">https://medium.com/media/5cd9f4152d07a1c75938d8204bf0d668/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e771b1ded3d826e65aad2bd47e2bff1/href">https://medium.com/media/2e771b1ded3d826e65aad2bd47e2bff1/href</a></iframe><h3>Gotchas</h3><ul><li>You may have to specify a minHeight on your list items, or otherwise specify the height when a placeholder is used. If you don’t, the adapter will query for (and the list will try to load) your whole list of 0-height items.</li><li>Don’t forget the first page is loaded when you call PagedList.Builder.build() — do this off the main thread!</li><li>Experiment with page sizes and prefetch windows. This is entirely dependent on your data.</li><li><a href="https://medium.com/@chriscraik/thanks-f38b1216a88">Already loaded objects are <strong>not</strong> unloaded</a>. If the user scrolls to the bottom of the list, the first items stay in memory. This is potentially a problem if your objects are large, or your list is long. Here I let <a href="http://square.github.io/picasso/">Picasso</a> load (and unload) the actual memory-intensive bitmaps for me — storing a list of Uris is cheap. This will hopefully be resolved before final release.</li><li>You <strong>must</strong> handle null objects returned from getItem if you enable placeholders, even if you never encounter them in your testing.</li><li>The loadRange call is not bounded to the size of the list; you need to do this yourself. It will happily handle results smaller than the requested count, however (i.e. when you’re at the end of the list).</li><li>If you’re using <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a>, look into <a href="https://developer.android.com/reference/android/arch/paging/LivePagedListProvider.html">LivePagedListProvider</a> as it will do most of this overhead for you.</li><li>The library is still in alpha at the time of this writing; the APIs described here could still change before release.</li></ul><h3>Additional Resources</h3><p>I initially learned about the Paging Library on the <a href="http://fragmentedpodcast.com/episodes/97/">Fragmented Podcast</a> where <a href="https://medium.com/u/d5885adb1ddf">Florina Muntenescu</a> talked about it with Donn and Kaushik. In addition to talking about the Paging Library, she touches on some other issues with regular Cursor-based queries. It’s well worth a listen. She also <a href="https://www.youtube.com/watch?v=Ts-uxYiBEQ8&amp;feature=youtu.be&amp;t=856">covered the library in her talk at GDD Europe</a>.</p><p>If you’re looking for more detail on the Paging Library, or your use-case doesn’t quite fit my example here, then <a href="https://developer.android.com/topic/libraries/architecture/paging.html">the official documentation</a> is always a great place to start.</p><p>Finally, I’d recommend looking at the source code directly. I spent a lot of time diving into the source while figuring this out — it’s clear and easy to read, and you can look at it right inside Android Studio.</p><p><em>Originally published at </em><a href="http://speakman.net.nz/blog/2017/10/09/asynchronously-loading-data-using-googles-paging-library/"><em>speakman.net.nz</em></a><em> on October 9, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d87fa411fa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>