<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.7.3">Jekyll</generator><link href="http://vaughandroid.me/feed.xml" rel="self" type="application/atom+xml" /><link href="http://vaughandroid.me/" rel="alternate" type="text/html" /><updated>2018-07-15T20:36:00+01:00</updated><id>http://vaughandroid.me/</id><title type="html">Vaughandroid blog</title><subtitle>Software development blog. Mostly Android and Java, and hopefully of some use to someone out there.</subtitle><entry><title type="html">Revisiting Fragments in 2018</title><link href="http://vaughandroid.me/2018/07/15/revisiting-fragments-in-2018/" rel="alternate" type="text/html" title="Revisiting Fragments in 2018" /><published>2018-07-15T00:00:00+01:00</published><updated>2018-07-15T00:00:00+01:00</updated><id>http://vaughandroid.me/2018/07/15/revisiting-fragments-in-2018</id><content type="html" xml:base="http://vaughandroid.me/2018/07/15/revisiting-fragments-in-2018/">&lt;p&gt;&lt;strong&gt;Or: How I stopped worrying and learned to love Fragments.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Fragments have been a contentious topic in the Android developer community pretty much since they were first introduced. Ever since I read Square’s influential blog post, &lt;a href=&quot;https://medium.com/square-corner-blog/advocating-against-android-fragments-81fd0b462c97&quot;&gt;Advocating Against Android Fragments&lt;/a&gt; I have been firmly in the anti-Fragment camp. Recently, I’ve had cause to revisit Fragments. As it turns out, I think it might be time to switch sides.&lt;/p&gt;

&lt;p&gt;In this post, I review the main problems with Fragments, then look into some of the recent changes that have alleviated those issues.&lt;/p&gt;

&lt;h2 id=&quot;what-was-wrong-with-fragments-anyway&quot;&gt;What was wrong with Fragments anyway?&lt;/h2&gt;
&lt;p&gt;When Fragments were first introduced way back in 2011, the main goal was to have a mechanism for creating modular, reusable, and largely self-sufficient components. This was an excellent goal, but the problems quickly arose. As I see it, the main issues were as follows:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Fragments had &lt;strong&gt;a lot of responsibilities&lt;/strong&gt; to support, which made them challenging to implement correctly. E.g. lifecycle management, navigation state, composition, helping manage async operations.&lt;/li&gt;
  &lt;li&gt;The lifecycle was very &lt;strong&gt;complicated&lt;/strong&gt; (see &lt;a href=&quot;https://github.com/xxv/android-lifecycle&quot;&gt;here&lt;/a&gt;) especially when you consider that there were differences in behaviour between different Android versions.&lt;/li&gt;
  &lt;li&gt;The implementation was &lt;strong&gt;buggy&lt;/strong&gt;, and some areas (notably nested Fragments) suffered from a host of lingering issues. Often the bugs only arose in edge cases, and were very tricky to work around.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;so-what-has-changed&quot;&gt;So what has changed?&lt;/h2&gt;
&lt;p&gt;In the past couple of years Google has doubled down on Fragment support, and they have made this clear at Google I/O ’17 and ’18. Fragments are being given a central role in the new &lt;a href=&quot;https://developer.android.com/jetpack/arch/&quot;&gt;Architecture Components libraries&lt;/a&gt;, and Google are now &lt;a href=&quot;https://www.reddit.com/r/androiddev/comments/8i73ic/its_official_google_officially_recommends_single/&quot;&gt;advocating&lt;/a&gt; a single-Activity, multi-Fragment architecture.&lt;/p&gt;

&lt;h3 id=&quot;bug-fixes&quot;&gt;Bug fixes&lt;/h3&gt;
&lt;p&gt;Google have clearly been putting concerted effort into fixing bugs. I’m not going to try to list all of the issues that have been addressed, but in my investigations the only issues I came across have already been resolved in the AndroidX 1.0.0-beta builds.&lt;/p&gt;

&lt;h3 id=&quot;new-library-support&quot;&gt;New library support&lt;/h3&gt;
&lt;p&gt;Many of the new Architecture Components are designed to handle a smaller subset of the responsibilities owned by Fragments - we now have straightforward, “official” means of delegating the responsibilities out to other classes. They also smooth over a lot of the tricky edge cases that users of Fragments have previously had to deal with. Taken collectively, they have a massive impact on how easy it is to work with Fragments.&lt;/p&gt;

&lt;h4 id=&quot;lifecycle&quot;&gt;Lifecycle&lt;/h4&gt;
&lt;p&gt;For me, the main benefit of the Lifecycle library is that it manages to put a simplified, clean and consistent wrapper around the mess that exists under the hood. It is simplified to something like this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/simplified_fragment_lifecycle.png&quot; alt=&quot;Simplified lifecycle diagram&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Google have even taken steps to ensure that &lt;code class=&quot;highlighter-rouge&quot;&gt;onSaveInstanceState()&lt;/code&gt; is called at a consistent point in the lifecycle. (See &lt;a href=&quot;https://developer.android.com/topic/libraries/architecture/lifecycle#onStop-and-savedState&quot;&gt;here&lt;/a&gt;). Also, in the AndroidX 1.0.0 release, Google have seen fit to recognise that the Fragment’s &lt;em&gt;View&lt;/em&gt; has its own lifecycle. (See &lt;a href=&quot;https://developer.android.com/reference/kotlin/androidx/fragment/app/Fragment#getviewlifecycleowner&quot;&gt;here&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;Previously, in order to write a well-behaved Fragment you essentially needed to implement a state machine which could keep track of multiple system callbacks to determine how to act appropriately. As far as I can see, we’ve now moved to a situation where we don’t need to track any state internally. This is a &lt;em&gt;huge&lt;/em&gt; win in terms of ease of implementation.&lt;/p&gt;

&lt;h4 id=&quot;viewmodel&quot;&gt;ViewModel&lt;/h4&gt;
&lt;p&gt;I find the name confusing, but ViewModels are great. In essence, they give you an object that is bound to the &lt;em&gt;logical&lt;/em&gt; lifecycle&lt;sup id=&quot;fnref:1&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; of a Fragment (or an Activity). It’s great to finally have an “official” mechanism for this.&lt;/p&gt;

&lt;p&gt;The ViewModel becomes the owner for the transitive state of the Fragment, including asynchronous operations.&lt;/p&gt;

&lt;h4 id=&quot;livedata&quot;&gt;LiveData&lt;/h4&gt;
&lt;p&gt;Lets you perform async operations without having to worry about memory leaks or updating he UI after &lt;code class=&quot;highlighter-rouge&quot;&gt;onSaveInstanceState()&lt;/code&gt;. Lovely!&lt;/p&gt;

&lt;h4 id=&quot;navigation&quot;&gt;Navigation&lt;/h4&gt;
&lt;p&gt;Honestly, I haven’t looked into this one in detail yet, but its role is to take over navigation responsibilities from the Fragment which definitely a good idea.&lt;/p&gt;

&lt;h2 id=&quot;in-conclusion&quot;&gt;In conclusion&lt;/h2&gt;
&lt;p&gt;I still don’t have enough real-world experience with the new libraries to make a decisive call. I certainly don’t think Fragments are perfect - even with the new libraries, there are some wrinkles remaining. There are other things I still haven’t figured out yet, like the best approach to testing. What I will say is that I am very encouraged by my experience so far. Using the new libraries, it is now possible to write lightweight Fragments which just do  I’m tentatively changing my assessment of Fragments from “actively harmful” to “actually useful”.&lt;/p&gt;

&lt;p&gt;It’s worth mentioning that there are still perfectly sound - possibly better - alternatives. You can stick with Activities, use a library like &lt;a href=&quot;https://github.com/bluelinelabs/Conductor&quot;&gt;Conductor&lt;/a&gt;, or roll your own solution. The playing field isn’t exactly level though: many teams will use Fragments simply because they are Google’s recommended approach. (I make no judgements here - there are valid reasons for doing this.)&lt;/p&gt;

&lt;p&gt;If, like me, you hated the ‘old’ Fragments, I’d encourage you to try the ‘new’ ones. You might be surprised! You’re likely to need to use them sooner or later, so I think it’s worth getting comfortable with them.&lt;/p&gt;

&lt;div class=&quot;footnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot;&gt;
      &lt;p&gt;This isn’t &lt;em&gt;quite&lt;/em&gt; true, as they don’t survive the process being killed by the system. There’s a brilliant blog post about that &lt;a href=&quot;https://medium.com/google-developers/viewmodels-persistence-onsaveinstancestate-restoring-ui-state-and-loaders-fc7cc4a6c090&quot;&gt;here&lt;/a&gt;. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;</content><author><name></name></author><category term="android," /><category term="fragments," /><category term="androidx" /><summary type="html">Or: How I stopped worrying and learned to love Fragments.</summary></entry><entry><title type="html">Comment annotations</title><link href="http://vaughandroid.me/2017/04/14/comment-annotations/" rel="alternate" type="text/html" title="Comment annotations" /><published>2017-04-14T00:00:00+01:00</published><updated>2017-04-14T00:00:00+01:00</updated><id>http://vaughandroid.me/2017/04/14/comment-annotations</id><content type="html" xml:base="http://vaughandroid.me/2017/04/14/comment-annotations/">&lt;h2 id=&quot;comments&quot;&gt;Comments&lt;/h2&gt;

&lt;p&gt;How many times have you seen (or written) comments like these:&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// This needs tests
// Needs testing
// Need to test this
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Those comments are easy to write, but you only notice them when you’re looking at that bit of code.&lt;/p&gt;

&lt;p&gt;Let’s say you have some time to pay off some tech debt and you want to add some tests. How are you going to find that code again? A project-wide search for “test” is going to turn up words like “fastest” or the &lt;code class=&quot;highlighter-rouge&quot;&gt;@Test&lt;/code&gt; annotation, and a whole bunch of things like that.&lt;/p&gt;

&lt;p&gt;Similarly, what if you wanted to track the incidence of these of comments in your codebase over time? You’re never going to do it because the cost of writing the regex (or whatever filtering script you want to write) is always going to outweigh any benefit, and it’s&lt;/p&gt;

&lt;h2 id=&quot;annotations&quot;&gt;Annotations&lt;/h2&gt;

&lt;p&gt;The dictionary defines annotations as follows:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;an·no·ta·tion&lt;/em&gt;
/noun/
  a note of explanation or comment added to a text or diagram.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It’s right there in the definition. At heart, annotations are nothing more than comments about our code. We already have comments in Java though, so why not just use them? Well, because comments are &lt;em&gt;code&lt;/em&gt;, they are highly structured and tools (like your IDE, or CI) can make use of them easily.&lt;/p&gt;

&lt;p&gt;If I want to use IntelliJ find all the uses of &lt;code class=&quot;highlighter-rouge&quot;&gt;@Deprecated&lt;/code&gt; in my codebase, I just find all the references to that annotation. Similarly, I could easily write an annotation processor to count the uses of that or any other annotation in my codebase, for use in a CI report.&lt;/p&gt;

&lt;h2 id=&quot;custom-annotations-to-the-rescue&quot;&gt;Custom annotations to the rescue&lt;/h2&gt;

&lt;p&gt;So, how could we replace all those comments about missing tests with an annotation? Fortunately, custom annotations are easy to write in Java. Here’s a simple example:&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public @interface NeedsTests {
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We can probably do better than that though. This annotation is never going to be needed at runtime, and it wouldn’t make sense to put it on anything other than a method or a class, so let’s specify that:&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Retention(RetentionPolicy.SOURCE)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface NeedsTests {
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Better. But maybe we want to include some extra information, like an estimation of the effort it would take to write those tests. We can do that too:&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Retention(RetentionPolicy.SOURCE)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface NeedsTests {
    int estimatedMinutes();
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You can even specify defaults for optional default values if you want.&lt;/p&gt;

&lt;h2 id=&quot;other-ideas&quot;&gt;Other ideas&lt;/h2&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@NeedsTests&lt;/code&gt; is definitely my most used of these “comment annotations”, but here are some other ideas (I’ll leave their uses up to your imagination):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@NeedsRefactor&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@TechDebt&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@WTF&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@ToDo&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@LocaleSpecific&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;@NeedsLocalising&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Really, your imagination is the limit here. If you have any other ideas, I’d love to hear them in the comments section.&lt;/p&gt;</content><author><name></name></author><category term="java," /><category term="annotations," /><category term="comments," /><category term="metaprogramming" /><summary type="html">Comments</summary></entry><entry><title type="html">Test doubles and Mockito</title><link href="http://vaughandroid.me/2016/10/17/test-doubles-and-mockito/" rel="alternate" type="text/html" title="Test doubles and Mockito" /><published>2016-10-17T00:00:00+01:00</published><updated>2016-10-17T00:00:00+01:00</updated><id>http://vaughandroid.me/2016/10/17/test-doubles-and-mockito</id><content type="html" xml:base="http://vaughandroid.me/2016/10/17/test-doubles-and-mockito/">&lt;p&gt;I want to be clear up front: I’m a big fan of &lt;a href=&quot;http://mockito.org&quot;&gt;Mockito&lt;/a&gt;. It’s very easy to use, and quite powerful. It has saved me a ton of time when writing unit tests. With that said, I’m going to grumble about it for most of this post.&lt;/p&gt;

&lt;p&gt;My main gripe with Mockito is it plays fast and loose with naming conventions for test doubles. The terminology we use for test doubles can get a bit muddled at the best of times, and Mockito pretty much stomps all over it.&lt;/p&gt;

&lt;h2 id=&quot;test-doubles&quot;&gt;Test doubles&lt;/h2&gt;
&lt;p&gt;You might be asking “what are test doubles?” You might know them as “mocks” or “stubs”. (This is actually part of the problem, as we’ll see.) We can define a test double as &lt;em&gt;any object we substitute for a production object, for testing purposes&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;That definition is pretty vague. Most of my test doubles just return some fixed values - can’t we have a specific name for those? What about ones that record interactions? In his book &lt;a href=&quot;http://xunitpatterns.com/index.html&quot;&gt;XUnit Test Patterns&lt;/a&gt;, Gerard Meszaros did us all a favour and came up with &lt;a href=&quot;http://xunitpatterns.com/Test%20Double.html&quot;&gt;5 different categories&lt;/a&gt;. Briefly, they are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Stubs&lt;/strong&gt; provide predefined (“canned”) responses to method calls, returning a value or throwing an exception.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spies&lt;/strong&gt; are stubs that record their interactions, for later verification.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dummies&lt;/strong&gt; are placeholders which are used only to satisfy method/constructor parameters. The code being tested shouldn’t actually interact with the dummy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mocks&lt;/strong&gt; are configured with a set of expected interactions, which are verified later.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fakes&lt;/strong&gt; are different from other test doubles in that they actually implement real behaviour, albeit in a simplified form.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This was a step forward, and it became popular with the help of people like Martin Fowler - see his famous article &lt;a href=&quot;http://martinfowler.com/articles/mocksArentStubs.html&quot;&gt;mocks aren’t stubs&lt;/a&gt;. This gave us all a common vocabulary to use to talk about this stuff.&lt;/p&gt;

&lt;h2 id=&quot;mockito&quot;&gt;Mockito&lt;/h2&gt;
&lt;p&gt;So, along comes Mockito, which gives us 2 methods (and 2 matching annotations) for creating test doubles:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.mock()&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;@Mock&lt;/code&gt;
 When you call &lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.mock(Thing.class)&lt;/code&gt;, Mockito generates a subclass of &lt;code class=&quot;highlighter-rouge&quot;&gt;Thing&lt;/code&gt; (or an implementing class if &lt;code class=&quot;highlighter-rouge&quot;&gt;Thing&lt;/code&gt; is an interface) on the fly, and returns an instance of that class. Depending on what you then do to that instance, it can be used as a stub, a spy, a dummy, or a mock.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.spy()&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;@Spy&lt;/code&gt;
 The difference with &lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.mock()&lt;/code&gt; is that rather than using default return values and having no behaviour, the default behaviour here is to delegate to &lt;code class=&quot;highlighter-rouge&quot;&gt;thing&lt;/code&gt; (or an instance of the class if &lt;code class=&quot;highlighter-rouge&quot;&gt;thing&lt;/code&gt; is an instance of &lt;code class=&quot;highlighter-rouge&quot;&gt;Class&lt;/code&gt;). You get the behaviour of &lt;code class=&quot;highlighter-rouge&quot;&gt;thing&lt;/code&gt;, with the ability to record any interactions with it and provide override methods with stubbed implementations. The normal term for this sort of test double is a &lt;strong&gt;partial test double&lt;/strong&gt;. (Some people call them &lt;strong&gt;partial mocks&lt;/strong&gt;, but I obviously take issue with that!)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;is-this-really-that-big-a-deal&quot;&gt;Is this really that big a deal?&lt;/h2&gt;
&lt;p&gt;Names are powerful. Using clear, accurate names helps others immediately latch onto concepts - they provide mental shortcuts we can all share. It’s &lt;em&gt;jargon&lt;/em&gt;, and we can infer its value from the fact we see it used everywhere.&lt;/p&gt;

&lt;p&gt;As an example, look at design patterns. They encapsulate complicated concepts into simple names. If you see a class called &lt;code class=&quot;highlighter-rouge&quot;&gt;UrlFactory&lt;/code&gt; you can immediately guess at how it works. If I say “X just delegates to an instance of Y”, you immediately know what I’m talking about.&lt;/p&gt;

&lt;p&gt;If we use overly-vague names, we don’t get to take any of those mental shortcuts. Imagine trying to describe OO programming to someone without using the words “class”, or “object”. It would be really hard! You’d probably end up coming up with new names for those concepts.&lt;/p&gt;

&lt;p&gt;Now imagine someone explaining OO programming to you, but they keep mixing up those terms. That’s even worse! This is what Mockito is doing.&lt;/p&gt;

&lt;h2 id=&quot;examples&quot;&gt;Examples&lt;/h2&gt;
&lt;p&gt;Let’s look at some examples. You’ll see that Mockito doesn’t differentiate between the different types based on name - you have to look at how the objects are used to work out which type of double they are.&lt;/p&gt;

&lt;h3 id=&quot;mocks&quot;&gt;Mocks&lt;/h3&gt;
&lt;p&gt;A simple test using a mock in Mockito goes something like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// ARRANGE
// Throw an exception for any unexpected interactions, by specifying a default answer.
Thing mockThing = mock(Thing.class, new Answer&amp;lt;Object&amp;gt;() {
  @Override public Object answer(InvocationOnMock invocation) throws Throwable {
    throw new RuntimeException(&quot;Unexpected interaction!&quot;);
  }
});

// Set up expected interactions.
when(mockThing.getString()).thenReturn(&quot;result&quot;);

// ACT...

// ASSERT
// Verify expected methods were called.
verify(mockThing).getString();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Side note:&lt;/strong&gt; Notice that we have to explicitly call &lt;code class=&quot;highlighter-rouge&quot;&gt;verify()&lt;/code&gt; for the same methods that we set up expectations for at the beginning. There’s no &lt;code class=&quot;highlighter-rouge&quot;&gt;verifyOnlyExpected()&lt;/code&gt; method. It turns out, Mockito’s support for mocks isn’t actually that great!&lt;/p&gt;

&lt;h3 id=&quot;spies&quot;&gt;Spies&lt;/h3&gt;
&lt;p&gt;Another simple test:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// ARRANGE
Thing spyThing = mock(Thing.class);

// Override default method stub.
when(spyThing.getString()).thenReturn(&quot;result&quot;);

// ACT...

// ASSERT
// Verify expected methods were called.
verify(spyThing).getString();
verifyNoMoreInteractions(spyThing);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The only thing which changed here is that we don’t specify a default answer. (On a side note, I hope you find the &lt;code class=&quot;highlighter-rouge&quot;&gt;spy = mock()&lt;/code&gt; bit in the first line as jarring as I do.)&lt;/p&gt;

&lt;h3 id=&quot;stubs&quot;&gt;Stubs&lt;/h3&gt;
&lt;p&gt;Another simple test:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// ARRANGE
Thing stubThing = mock(Thing.class);

// Override default method stub.
when(stubThing.getString()).thenReturn(&quot;result&quot;);

// ACT, ASSERT...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Look familiar? Same as the spy, but we lost the verification at the end.&lt;/p&gt;

&lt;h4 id=&quot;the-manual-approach&quot;&gt;The manual approach&lt;/h4&gt;
&lt;p&gt;I feel obliged to point out that it should generally be as easy, or easier, to write stubs manually than it is to use Mockito. If you find yourself using Mockito to stub a class because it has 10 methods and your test only cares about 2 of them, then that’s a &lt;a href=&quot;https://en.wikipedia.org/wiki/Code_smell&quot;&gt;code smell&lt;/a&gt;. You might want to split up the class, or at least define separate interfaces for different bits of behaviour.&lt;/p&gt;

&lt;h3 id=&quot;dummies&quot;&gt;Dummies&lt;/h3&gt;
&lt;p&gt;Dummies are really simple:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// ARRANGE
Thing dummyThing = mock(Thing.class, new Answer&amp;lt;Object&amp;gt;() {
  @Override public Object answer(InvocationOnMock invocation) throws Throwable {
    throw new RuntimeException(&quot;Unexpected interaction!&quot;);
  }
});

// ACT, ASSERT...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is the same as the mock, but without setting up or validating any expected interactions.&lt;/p&gt;

&lt;h3 id=&quot;what-about-mockitospy&quot;&gt;What about &lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.spy()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;I mentioned this earlier, but it bears repeating: &lt;code class=&quot;highlighter-rouge&quot;&gt;Mockito.spy()&lt;/code&gt; gives you something commonly referred to as a &lt;em&gt;partial test double&lt;/em&gt;. It can function as a partial mock, a partial spy, or a partial stub. (Partial dummies don’t really make sense, for hopefully obvious reasons.)&lt;/p&gt;

&lt;p&gt;The use of partial mocks is almost always a code smell, but they can be a useful stopgap when working with legacy code.&lt;/p&gt;

&lt;p&gt;A simple test with a partial test double might look like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// ARRANGE
Thing partialMockThing = spy(new Thing(&quot;result&quot;));

// ACT...

// ASSERT
// Verify expected methods were called.
verify(partialMockThing).getString();
verifyNoMoreInteractions(partialMockThing);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;a-case-for-the-defence&quot;&gt;A case for the defence?&lt;/h2&gt;
&lt;p&gt;I’m not a mind reader, so I don’t know what the exact thought processes that led to Mockito functioning the way it does. I can suggest some possibilities though:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Software development is full of trade-offs, and we cope with this by prioritising certain features over others. In this case, the developers may have valued simplicity (of API and implementation) over precision.&lt;/li&gt;
  &lt;li&gt;The developers may have felt that the terminology established by Meszaros wasn’t worth following - maybe they felt it wasn’t ubiquitous enough, or maybe they thought it was undermined by the existing confusion between mocks, stubs and test doubles.&lt;/li&gt;
  &lt;li&gt;The really liked their pun on “mock”, but couldn’t come up with good ones for “spy” and “stub”. ;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The first thing I said was that I’m a big fan of Mockito, and I am. I think you should be, too! But I don’t think it’s perfect. Names matter, and Mockito breeds confusion where it could bring clarity.&lt;/p&gt;

&lt;p&gt;If you’ve never heard of test doubles, I hope this has been a good introduction. Even if you had heard of them before, I hope this post has been food for thought. (Especially if you happen to be one of the maintainers of Mockito!)&lt;/p&gt;</content><author><name></name></author><category term="testing," /><category term="unit" /><category term="testing," /><category term="test" /><category term="doubles," /><category term="mockito," /><category term="java," /><category term="dummies," /><category term="fakes," /><category term="mocks," /><category term="spies," /><category term="stubs" /><summary type="html">I want to be clear up front: I’m a big fan of Mockito. It’s very easy to use, and quite powerful. It has saved me a ton of time when writing unit tests. With that said, I’m going to grumble about it for most of this post.</summary></entry><entry><title type="html">Killing an emulator - not as simple as you might think</title><link href="http://vaughandroid.me/2016/05/27/killing-the-android-emulator/" rel="alternate" type="text/html" title="Killing an emulator - not as simple as you might think" /><published>2016-05-27T00:00:00+01:00</published><updated>2016-05-27T00:00:00+01:00</updated><id>http://vaughandroid.me/2016/05/27/killing-the-android-emulator</id><content type="html" xml:base="http://vaughandroid.me/2016/05/27/killing-the-android-emulator/">&lt;h3 id=&quot;background&quot;&gt;Background&lt;/h3&gt;

&lt;p&gt;I’ve been doing a bunch of work recently trying to fix up and improve our Android CI setup. I’m planning on doing a future series of posts on the topic, but I thought this warranted its own post since it concerns a recent update.&lt;/p&gt;

&lt;p&gt;If you’re running CI tests on an emulator, you’re going to need to restart it - ideally you want a freshly started emulator for every test run. This helps minimize the effects of bugs in the emulator itself, which are a fact of life for the time being.&lt;/p&gt;

&lt;p&gt;SDK Tools 25.1.6 (May 2016) includes this note in the &lt;a href=&quot;https://developer.android.com/studio/releases/sdk-tools.html&quot;&gt;release notes&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;To improve the security of the Android Emulator and to address a reported security vulnerability, the Android Emulator Console now requires authentication before you can enter commands. Enter the auth auth_token command after you telnet to an emulator instance. auth_token must match the contents of the .emulator_console_auth_token file in your home directory.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Great - they fixed a security vulnerability!&lt;sup id=&quot;fnref:1&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; Great, right?&lt;/p&gt;

&lt;h3 id=&quot;the-problem&quot;&gt;The problem&lt;/h3&gt;

&lt;p&gt;Unfortunately the extra auth requirement breaks &lt;code class=&quot;highlighter-rouge&quot;&gt;adb emu kill&lt;/code&gt;, which has long been the proper way to kill an emulator instance (though weirdly this doesn’t appear in the &lt;a href=&quot;https://developer.android.com/studio/command-line/shell.html#shellcommands&quot;&gt;current documentation&lt;/a&gt;). The command just fails silently now.&lt;/p&gt;

&lt;p&gt;Since &lt;code class=&quot;highlighter-rouge&quot;&gt;adb emu kill&lt;/code&gt; doesn’t work, we’re left with these options:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Disable the new authentication feature. You can do this by replacing the &lt;em&gt;.emulator_console_auth_token&lt;/em&gt; file with an empty file. (&lt;a href=&quot;https://developer.android.com/studio/run/emulator-commandline.html#console-session&quot;&gt;Source&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;Kill the emulator process with &lt;code class=&quot;highlighter-rouge&quot;&gt;kill -9&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Telnet in to the emulator, authenticate, and issue the &lt;code class=&quot;highlighter-rouge&quot;&gt;kill&lt;/code&gt; command there.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;disabling-authentication&quot;&gt;Disabling authentication&lt;/h4&gt;

&lt;p&gt;Disabling the authentication would probably be OK - since we’re just talking about CI tests we probably don’t care too much about securing it. The problem here is that the &lt;em&gt;.emulator_console_auth_token&lt;/em&gt; file lives in the user’s home directory. This system-level config is a pain in the arse for portability - you have to remember to change the system setting for every environment you want to run the CI scripts on. That also means exposing dev machines to the security vulnerability (if they ever want to run CI scripts locally).&lt;/p&gt;

&lt;h4 id=&quot;killing-the-process&quot;&gt;Killing the process&lt;/h4&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;kill -9&lt;/code&gt; is considered bad practice because you don’t give the process the chance to do any cleanup. That could mean a variety of bad things: corrupting the filesystem image, not closing ports correctly, etc. You’re opening the door to a host of potential issues.&lt;/p&gt;

&lt;h4 id=&quot;doing-it-the-right-way-hopefully&quot;&gt;Doing it the right way (hopefully)&lt;/h4&gt;

&lt;p&gt;So, option 3 it was! The below &lt;a href=&quot;http://expect.sourceforge.net/&quot;&gt;Expect&lt;/a&gt; script opens a telnet session to the emulator, authenticates, and then issues the kill command (this is different to &lt;code class=&quot;highlighter-rouge&quot;&gt;kill -9&lt;/code&gt; since it allows the emulator to shut down correctly). There’s not much else to say really, other than I hope you find it useful.&lt;/p&gt;

&lt;p&gt;Oh, and it’s my first Expect script, so please be kind. :)&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/vaughandroid/310c6d1d12f5473ea2e098982c77443f.js?file=kill-emulator.exp&quot;&gt; &lt;/script&gt;

&lt;div class=&quot;footnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot;&gt;
      &lt;p&gt;I’ll save my amazement that we have to worry about emulator security for another day. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;</content><author><name></name></author><category term="android," /><category term="emulator," /><category term="testing," /><category term="scripting," /><category term="continuous" /><category term="integration" /><summary type="html">Background</summary></entry></feed>