在我的应用程序中,我将 XML 文件的内容解析为两个数组。在我的单元测试中,如何从被测活动中获取这些 ArrayList,以便我可以测试它们的长度是否正确且内容是否正确?使用我目前使用的方法,尽管我知道解析工作正常,但数组始终为空。(解析方法在被测Activity的onCreate()方法中调用。)
@RunWith(RobolectricTestRunner.class)
public class TroubleShooterActivityTest {
private TroubleShooterActivity mActivity;
private Button mButton;
private TextView mTextView;
private ImageView mLogo;
private ArrayList<Page> mPageList;
private ArrayList<Answer> mAnswerList;
private int lengthPageArray = 7;
private int lengthAnswerArray = 7;
@Before
public void setUp() throws Exception {
mActivity = new TroubleShooterActivity();
mActivity.onCreate(null);
mButton = (Button) mActivity.findViewById(R.id.troubleShooter);
mTextView = (TextView) mActivity.findViewById(R.id.title);
mLogo = (ImageView) mActivity.findViewById(R.id.IntegralLogo);
mPageList = TroubleShooterActivity.pageList;
mAnswerList = TroubleShooterActivity.answerList;
}
@Test
public void testPreconditions() {
assertNotNull(mTextView);
assertNotNull(mLogo);
assertNotNull(mButton);
assertNotNull(mPageList);
assertNotNull(mAnswerList);
}
@Test
public void testArraysWereFilledCorrectly(){
assertEquals(mPageList.size(), lengthPageArray);
assertEquals(mAnswerList.size(), lengthAnswerArray);
}
来自 TroubleShooterActivity 的代码
public class TroubleShooterActivity extends OptionMenu {
/**Variables */
static ArrayList<Page> pageList;
static ArrayList<Answer> answerList;
/** onCreate() is called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parseXML();
Button Select = (Button) findViewById(R.id.troubleShooter);
/** assign behaviour to button*/
Select.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(TroubleShooterActivity.this, Question.class);
intent.putExtra("NextPageID", 1); //Pass next page ID to Question class
startActivity(intent);
}
});
}
public void parseXML(){
try {
/** Try handling XML */
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
/**Gets the input from the XML file stored in the res raw folder */
InputSource is = new InputSource(getResources().openRawResource(R.raw.trouble_shooter_content));
XMLHandler xmlHandler = new XMLHandler();
/** assign our handler */
xmlreader.setContentHandler(xmlHandler);
xmlreader.parse(new InputSource(is.getByteStream()));
pageList = XMLHandler.pageList;
answerList = XMLHandler.answerList;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
//Let the user know about the error
}
}