unit testing custom view

1,128 views
Skip to first unread message

WeyenDrote

unread,
Jun 11, 2011, 5:10:53 AM6/11/11
to Robolectric
For an application I am developing I subclassed RelativeLayout to
create a custom view, which I would like to test with Robolectric.

public class MyView extends RelativeLayout
{
public MyView (Context context, AttributeSet attrs)
{
super(context, attrs);

LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout mBarView = (RelativeLayout)
mInflater.inflate(R.layout.myview, null);
addView(mBarView);
}
}

The layout itself is a simple RelativeLayout containing LinearLayouts
with ImageButtons. I want to write a unittest to check that the
ImageButtons change resource when something happens. The following is
a test for the initial state:

@Test
public void shouldSetIconAOnButtonA()
{
MyView myView = new MyView(null, null);
ImageButton buttonA = (ImageButton)
myView.findViewById(R.id.buttonA);
ShadowImageView shadowImageView = Robolectric.shadowOf(buttonA);
assertThat(shadowImageView.getResourceId(),
equalTo(R.drawable.iconA));
}

While the code works in the application and the view is rendered
correctly, the unittest fails with a nullpointerexception; not
surprising as I pass null in the constructor. The question is: can
Robolectric perform these tests or help me pass a fake Context and
AttributeSet? Or should I load this view in a dummy Activity to get it
to test?

Tyler Schultz

unread,
Jun 11, 2011, 4:22:28 PM6/11/11
to robol...@googlegroups.com
Hi, I just wrote a blog post that explains how I like to test custom views:


I find specifying layout in java frustrating.  I prefer to create my views in xml, and put only the behavior in the java class. 

--Tyler
Reply all
Reply to author
Forward
0 new messages