Issue
In my app, I want to test button background is correct with what I expect. But I get Nullpointerexception error when try to get button background. I can not see where I wrong. My code below:
Button btnGetStarted = (Button) getActivity().findViewById(R.id.btnGetStarted);
Drawable actual = btnGetStarted.getBackground();
Drawable expect = getActivity().getResources().getDrawable(R.drawable.btn_active_normal);
assertTrue("Wrong button background", actual==expect);
Nullpointerexception at line `Drawable actual = btnGetStarted.getBackground();
I can not solve it after 2 days so I post it on here to looking for help.
Edit:
In xml file I set button background from a picture btn_getstarted.png
like this: android:background="@drawable/btn_getstarted"
Solution
Your button is null here. That's why you are not getting the drawable. Change the code in your test case like this and try :
private View inflaterView;
LayoutInflater i=(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflaterView=i.inflate(R.layout.you_layout_file, null);
Button btnGetStarted=(Button) inflaterView.findViewById(R.id.btnGetStarted);
Addition to this I think comparing two drawable like this is not the correct way. If both variables contain references to objects that 'look' the same, they are two different objects instances.So two drawable objects, will not return true on equals.
As a suggestion to test two drawable objects get the constantState associated to that Drawables.
btnGetStarted.getBackground().getConstantState.getConstantState().equals
(getResources().getDrawable(R.drawable.btn_getstarted).getConstantState())
Answered By - Zusee Weekin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.