我正在开发使用Android的java.xml.parsers.DocumentBuilder和DocumentBuilderFactory实现从XML文件加载信息的软件。 我正在编写对象的单元测试,我需要能够提供各种xml文件,这些文件将执行测试中的代码。 我正在使用Eclipse,并且有一个单独的Android测试项目。 我找不到将测试xml放入测试项目中的方法,以使被测代码可以打开文件。
如果我将文件放在测试项目的/ assets中,则被测试的代码看不到它。
如果我将文件放在要测试的代码的/ assets中,则当然可以看到文件,但是现在我只测试数据文件就使我的实际系统混乱了。
如果我手动将文件复制到/ sdcard / data目录,则可以从被测试的代码中打开它们,但这会干扰自动化测试。
关于如何具有不同的xml测试文件的任何建议都驻留在测试包中,但是对于被测代码可见。
这是我尝试构建单元测试的方法:
public class AppDescLoaderTest extends AndroidTestCase
{
private static final String SAMPLE_XML = "sample.xml";
private AppDescLoader m_appDescLoader;
private Application m_app;
protected void setUp() throws Exception
{
super.setUp();
m_app = new Application();
//call to system under test to load m_app using
//a sample xml file
m_appDescLoader = new AppDescLoader(m_app, SAMPLE_XML, getContext());
}
public void testLoad_ShouldPopulateDocument() throws Exception
{
m_appDescLoader.load();
}
}
由于SAMPLE_XML文件处于测试上下文中,因此无法使用,但是AndroidTestCase为被测系统提供了一个上下文,该系统无法从测试包中看到资产。
这是修改后的代码,适用于给出的每个答案:
public class AppDescLoaderTest extends InstrumentationTestCase
{
...
protected void setUp() throws Exception
{
super.setUp();
m_app = new Application();
//call to system under test to load m_app using
//a sample xml file
m_appDescLoader = new AppDescLoader(m_app, SAMPLE_XML, getInstrumentation().getContext());
}