关于Robolectric。当我在一个活动中有对象不是init时,我该如何测试该活动?

时间:2016-06-07 09:33:47

标签: android robolectric android-testing

当我这样写时 MyActivity activity = Robolectric.setupActivity(MyActivity.class);

它总是这样抛出:

java.lang.NullPointerException
    at com.printer.ui.activity.MyActivity.initView(MyActivity.java:309)
    at com.ui.activity.MyActivity.onCreate(MyActivity.java:114)

这一行是这样的:

fileTextView.setText(AppUtil.getFileNameNoEx(AppConfig.printFile.getName()));

AppConfig.printFile 为空,我该如何测试该活动?

1 个答案:

答案 0 :(得分:1)

快速修复您的测试:

AppConfig.printFile = new File();
MyActivity activity = Robolectric.setupActivity(MyActivity.class);

正确的解决方法是在活动意图中传递路径:

public class MyActivity {
   public static final String FILE_PATH = "FILE_PATH";

   public void onCreate(Bundle bundle) {
      super.onCreate(bundle);

      String path = getIntent().getStringExtra(FILE_PATH);
      ...
   } 
   ...
}

Intent myActivityIntent = new Intent(this, MyActivity.class);
intent.putExtra(MyActivity.FILE_PATH, "path");
startActivity(intent);

尽量避免使用静态http://www.endran.nl/blog/death-to-statics/