Thursday, December 31, 2015

Mock Application in Espresso for Dependency Injection

I read this great post by Artem Zinnatullin on How to mock dependencies in Unit, Integration and Functional tests; Dagger, Robolectric and Instrumentation. The part I like the best is to use a different application in tests to provide different dependencies, and I decided to try it with Espresso.

Mock application via custom test runner

My current approach to dependency injection is to expose a setComponent function in my application for tests to supply the test component, which is not great because ideally the application should not have test-specific code.

The new approach is to subclass the application in the androidTest folder and load it during tests via a custom test runner.

public class DemoApplication extends Application {
  private final DemoComponent component = createComponent();

  protected DemoComponent createComponent() {
    return DaggerDemoApplication_ApplicationComponent.builder()
        .clockModule(new ClockModule())
        .build();
  }

  public DemoComponent component() {
    return component;
  }
}

In the application we initialize a DemoComponent with createComponent() and stash it in a final variable to be used later.

public class MockDemoApplication extends DemoApplication {
  @Override
  protected DemoComponent createComponent() {
    return DaggerMainActivityTest_TestComponent.builder()
        .mockClockModule(new MockClockModule())
        .build();
  }
}

For testing, we subclass our application and override createComponent to supply the test component instead.

To use the mock application in tests, we need a custom test runner:

public class MockTestRunner extends AndroidJUnitRunner {
  @Override
  public Application newApplication(
      ClassLoader cl, String className, Context context)
      throws InstantiationException, 
             IllegalAccessException, 
             ClassNotFoundException {
    return super.newApplication(
      cl, MockDemoApplication.class.getName(), context);
  }
}

We give it MockDemoApplication.class.getName() as the class name so the test runner will load the mock application instead of the main one.

Per application vs per test

This approach is slightly different from setComponent because we initialize the test component only once, rather than before each test method. Make sure you clear the state of your test modules before each test so run each test in from a clean slate.

Source code

I have updated two of my repositories to use this approach:

Like this article? Take a look at the outline of my Espresso book and fill in this form to push me to write it! Also check out the published courses: https://gumroad.com/chiuki

Thursday, December 24, 2015

Learn to celebrate

Work hard and you shall be rewarded. I don't know where I got that idea, but that was how I operated for a long time. Turns out hard work does not count if nobody knows about it.

This is especially important during performance reviews. How do you let others know the good work you have been doing? To most of us, it is not natural to toot your own horn. But like most skills, it can be learned.

Step one: Reframe. Rather than viewing it as bragging, look at it as celebration. Celebrate your achievements, big and small.

Donuts

I really like how Lara Hogan does it. She gets herself a donut whenever something awesome happened in her career, and makes its significance known to those around her. Check out her Donut Manifesto!

The boring list

If donut is not your thing, you can do with the good ol' list. Send a weekly summary email to your team with a few bullet points of what you have done.

Or you can take it a notch up and add some prose around it. I have started doing that with my newsletter, sending out about once a month, and it has been a great way to look back and take stock my accomplishments.

Celebrate now

End of year is an excellent reason to celebrate. Here is my list: blog.sqisland.com/2015/12/my-2015.html

Your turn! Write a blog post for your 2015 accomplishments (do it on medium if you don't have a blog) and post a link in the comments. Let's celebrate!

My 2015

End of year offers a great opportunity to take stock at what I have done. Here are my highlights.

Public Speaking

This year I have shifted my efforts from giving talks to enabling others to do so.

  • I started the Technically Speaking newsletter (please subscribe!) last year with Cate Huston, and we continue to publish one issue per week.
  • I ran a grassroot campaign to get more women to speak at Droidcon NYC, resulting in 22% female speakers. I hope this will serve as a blueprint for others, especially conference organizers, to push the limits.
  • In September I gave my very first keynote speech, sharing my tips to blog and speak more. Please watch it and let me know if it helps you get started and level up on your blogging and speaking!

Android Dialogs

I started a YouTube channel with Huyen Tue Dao to interview people in the Android community. It has been really fun picking up video production, and we have been adding more visuals to aid explanations.

Sketchnotes

This came as a total surprise, as I have always considered myself as someone who cannot draw. Turns out sketchnoting is more about constraint satisfaction than drawing. And as an engineer, I am extremely good at that.

I really enjoyed sharing my learnings from conferences this way. I have scanned all my sketchnotes from 2015 into a PDF collection:


gum.co/Sketchnotes2015

It is free to download, but you can also chip in a few dollars if you'd like to support my work.

Courses

I published two classes with Pluralsight this year:

I also drafted a outline for my Espresso book, and wrote a course from it:


gum.co/AndroidTestSharedPref

2016

A few of these projects were surprises. I never thought I'd be producing one video a week, or be known for taking graphic notes! I have no idea what 2016 will bring, but I am looking forward to it!

Monday, December 14, 2015

Use Quicktime to record your own talk

There are many reasons why you may want to your talk recorded:

  • You can watch it again yourself to look for things you can improve.
  • People at your talk can watch it to refresh their memories and share it with their friends.
  • People not at the event get to watch you talk.
  • Conference organizers get an idea what they are getting when they accept your talk proposals.

However, not all meetups and conferences record their talks. If they don't, you can do it yourself with a screen record. Quicktime is the easiest way to do it on a mac.

Screen record with Quicktime

  1. Select File → New Screen Recording.

  2. Click on the down arrow next to the red button to make sure you are recording the sound.

  3. Press the red button to start recording.

Second camera

If you want to be fancy, you can set up a second camera to record your face. I use a camcorder, but you can also have a friend record you with another laptop.

On the second laptop, choose File → New Movie Recording.

You can either turn the laptop around to use the built-in camera, or attach a USB webcam. Make sure you record the sound as well so you can use it to sync up with the screen capture from your laptop.

You will need to put the two clips together. I use Camtasia as my video editor, but iMovie probably works too.

Here is an example of a talk that I recorded myself:

Tips

  • Try it before the actual event to make sure you know how this works.
  • Clear up enough disk space for the video. You will need gigabytes!
  • Put a post-it on your laptop so you don't forget to start recording at the beginning of your talk.
  • From @JakeWharton: Record the screen on which the presentation is being displayed. Don't record presenter display!
  • From +SebastianoPoggi: You can also use VLC for added quality and stability (QT crashes write often). Plus not Mac only :)

Friday, November 27, 2015

Android Dev Summit: Amazing!

Google ran its first Android Dev Summit this November, and I gotta say, it was amazing.

Session Videos

The AV team edited and posted the videos within 2 hours of the talk, so everyone can enjoy the content. My absolute favorite was "Android Studio for Experts". So many tips and tricks!

Check out the playlist for more.

Sketchnotes

I took many sketchnotes during the summit. Here are a few of them:

I will scan them and add the high-resolution version to this PDF when I get home: gum.co/Sketchnotes2015. Download the current edition to get an email when it is updated.

Encore!

Android Dev Summit gave us Android developer lots of in-depth technical content and easy access to the team. I hope Google will do it again!

Saturday, November 7, 2015

2016 Speaking Goals

I started public speaking in 2012 with a New Year's Resolution. It was a great way to gather my thoughts on what I want to share, and have grown a lot since then as a speaker. Last year Cate and I started Technically Speaking to help other people to start speaking at technical conferences, and we would like to take advantage of the new year to get more people to set speaking goals.

As a part of our birthday celebrations, Technically Speaking is offering 1-hour mentoring sessions to help people turn ideas into reality.

To get the ball rolling, here are my goals:

  1. Revamp my speaker page
  2. Give a keynote
  3. Help 3 first-time speakers give talks at conferences

Revamp my speaker page

Currently my speaker page is a list of all the talks I have given. I would like to update it to highlight certain talks, embed some videos, and also state my speaking requirements. I really like how Rachel Andrew explains her policy, and would like to create something similiar.

Give a keynote

I gave my very first keynote at Android Summit this year. I prepared a lot more than a tech talk, but it was also a lot more rewarding, because as a keynote speaker I try to motivate people to step out of their comfort zone. I would like to do that again.

Help 3 first-time speakers give talks at conferences

Navigating the speaking scene can be quite daunting, especially if you have never given a talk before. I broadcast tips and tricks on Technically Speaking, but nothing beats 1-on-1 mentoring, both for the mentor and mentee. As a mentor, I get the satisfaction of seeing concrete results.

Help me help you achieve your goals and mine. Post yours!

Friday, November 6, 2015

MVP: The Missing Link

I have been wanting to learn the Model View Presenter pattern for a while, and was super excited to get Michael Cameron to give a talk on it at GDG Boulder last night.

View Interface

I have this vague notion that MVP is good for JUnit testing, and I finally figured out why. The secret, the missing link, is View Interface, which is not a part of the MVP acronym. View Interface defines the contract between the view and the presenter, allowing you to mock one while testing the other.

With View Interface, you can compartmentalize your Android UI code into the view (typically a Fragment or Activity), which communicates with your presenter solely through the View Interface. This separation allows you to mock your View Interface with zero Android code, which means you can test your presenter with JUnit on the JVM.

Mocking via build flavors

Mocking is essential for hermetic testing, but people are often intimated by dependency injection frameworks like Dagger. If you prefer, you can provide mocks to your test using build flavors. An excellent technique!

Mockito

Mockito is a great mocking framework with a fluent API. One very nice feature is mocking via annotations. To use that, annotate the fields you want to mock with @Mock, and initialize them all with MockitoAnnotations.initMocks() in your @Before function.

@Mock
private MyThing myThing;

@Mock
private OtherThing otherThing;

@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
}

This is equivalent to:

private MyThing myThing;
private OtherThing otherThing;

@Before public void setUp() throws Exception {
  myThing = Mockito.mock(MyThing.class);
  otherThing = Mockito.mock(OtherThing.class);
}

Slides: http://www.slideshare.net/DarxVal/model-view-presenter-presentation

Codelab

Google has published the excellent Android Testing Codelab going through an app with the MVP architecture. You can see JUnit and Espresso testing in action, mocks via build flavors, and various other techniques. Go check it out!