Reputation: 5732
I have a Customview class and I want to write a simple test for it. At first I want to check if the LayoutParams are set.
CustomView Class
public class CustomView extends FrameLayout {
public CustomView(@NonNull Context context) {
super(context);
initFrameLayout();
}
public void initFrameLayout() {
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
this.setLayoutParams(layoutParams);
}
}
CustomViewTest class
public class CustomViewTest {
@Test
public void viewInitializedCorrectly() {
Context context = mock(Context.class);
CustomView customView = new CustomView(context);
int expectedViewWidth = FrameLayout.LayoutParams.MATCH_PARENT;
assertEquals(expectedViewWidth, customView.getLayoutParams().width);
}
The test fails with an NullPointerException. I inspected the method with the debugger and I note, that the FrameLayout Object exists but without parameter. Should I mock the CustomView.class
too?
Upvotes: 2
Views: 4852
Reputation: 21407
There are a number of different types of tests in Android. Local Unit Tests run in your IDE on your laptop or desktop and Instrumented Unit Tests run on a device.
Local Unit Tests do not ordinarily have access to Android SDK classes like FrameLayout
. Instead, you get stubbed out versions of these classes that return null. This explains the NullPointerException
For getting around the error, you could mock FrameLayout
manually or use something like Robolectric which is a framework that provides test doubles called "shadows" of Android classes like FrameLayout
.
However, in general custom views are poorly suited for unit testing since they cannot have mocks injected easily (since they are inflated by the OS from XML attributes) and the tests can often degenerate into a reverse implementation of the class. If the custom view does require testing beyond "it looks right" a better option may be to write Espresso automated UI tests which are more suited for that sort of thing.
Upvotes: 4