Butterknife: Binding views in Robolectric tests

Created on 27 May 2016  路  4Comments  路  Source: JakeWharton/butterknife

I would like to use Butterknife to reduce boilerplate code in Robolectric tests like it does with the production code. Butterknife works for me in activities and the original tests work when I switch the activity's views to use Butterknife binding.

However, it doesn't work as I expect in a test case using Robolectric (3.0):

@BindView(R.id.test_button) Button testButton;

@Before
public void setup() {
    activityUnderTest = Robolectric.setupActivity(ActivityUnderTest.class);
    ButterKnife.bind(this, activityUnderTest);
}

@Test
public void checkTestButton() {
    testButton.performClick();
}

The views are not bound, and the test will raise a NullPointerException for attempting to use the testButton reference.

I figured this would work since what I currently have is:
testButton = (Button) activityUnderTest.findViewById(R.id.test_button);

From the documentation, it seems that this should generate the previous statement:
ButterKnife.bind(this, activityUnderTest)

Is it possible to get this to work?

Most helpful comment

Specify butterknife-compiler as a testApt dependency and it should work fine.

All 4 comments

Specify butterknife-compiler as a testApt dependency and it should work fine.

Thank you!

Just wanted to update that if you are using android gradle plugin 2.2.+ you will need to specify butterknife-compiler as a testAnnotationProcessor and androidTestAnnotationProcessor instead of a testApt.

@JakeWharton can you please eloborate how to Specify butterknife-compiler as a testApt dependency.

Was this page helpful?
0 / 5 - 0 ratings