android测试用例中获取按钮背景时出现Nullpointerexception
在我的应用程序中,我想测试按钮背景是否与我期望的一致。但当我尝试获取按钮背景时,会出现Nullpointerexception错误。我看不出我错在哪里。 我的代码如下:android测试用例中获取按钮背景时出现Nullpointerexception,android,unit-testing,android-testing,Android,Unit Testing,Android Testing,在我的应用程序中,我想测试按钮背景是否与我期望的一致。但当我尝试获取按钮背景时,会出现Nullpointerexception错误。我看不出我错在哪里。 我的代码如下: Button btnGetStarted = (Button) getActivity().findViewById(R.id.btnGetStarted); Drawable actual = btnGetStarted.getBackground(); Drawable expect = getAct
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);
第`Drawable actual=btnGetStarted.getBackground()行的Nullpointerexception
我无法解决它后2天,所以我张贴在这里寻求帮助
编辑:
在xml文件中,我从图片
btn_getstarted.png
中设置按钮背景,如下所示:android:background=“@drawable/btn_getstarted”
检查xml中的按钮id是否为“@+id/btnGetStarted”。尝试通过LayoutFlater来扩大布局,并在视图中找到按钮。findViewById()您的按钮在此处为空。这就是为什么你没有得到可拖动的。
按如下方式更改测试用例中的代码,然后尝试:
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);
除此之外,我认为比较两个像这样的可绘制的不是正确的方法。
如果两个变量都包含对“外观”相同的对象的引用,则它们是两个不同的对象实例。因此,两个可绘制对象在相等时不会返回true
建议测试两个可绘制对象获取与该可绘制对象关联的常量状态
btnGetStarted.getBackground().getConstantState.getConstantState().equals
(getResources().getDrawable(R.drawable.btn_getstarted).getConstantState())
发布你的onCreate和你正在使用的xml你确定这里的btnGetStarted不是空的吗?我认为
onCreate
代码没有问题,只是findViewById
和setOnClickListener
只发布xml布局文件是的,我确定这里的按钮不是空的。我尝试了你的代码,它运行得很好。非常感谢,不用担心。很高兴帮助你。