I have setup an android test project that runs junit tests. It\'s using two eclipse projects \"Application\" and \"ApplicationTest\" where my tests are in the \"ApplicationT
With build tools 3.0.0 you can use ActivityTestRule
@RunWith(AndroidJUnit4::class)
@SmallTest
class MainActivityTest {
@Rule
@JvmField
var mainActivityRule = ActivityTestRule(MainActivity::class.java)
private val baseUrl: String
get() {
return mainActivityRule.activity.getString(R.string.base_url)
}
@Test
fun launchingWithMovieIntent() {
assert.that(baseUrl, equalTo("someValue")
}
}
}
I would suggest extending ActivityTestCase
instead of AndroidTestCase
. You can than access test project resources via
getInstrumentation().getContext().getResources().openRawResource(R.raw.your_res)
.
Dummy test case example:
public class Test extends ActivityTestCase {
public void testFoo() {
// .. test project environment
Context testContext = getInstrumentation().getContext();
Resources testRes = testContext.getResources();
InputStream ts = testRes.openRawResource(R.raw.your_res);
assertNotNull(testRes);
}
}
And then in test methods use getInstrumentation().getTargetContext()
wherever you used getContext()
in your AndroidTestCase
extension.
Since Android Gradle Plugin
version 1.1 you haven't to use Instrumentation
to load file resource.
I wrote here how to do it with POJO unit test case.
I derived the test case as follows:
class MyTest extends InstrumentationTestCase {
void setUp() {
InputStream is = getInstrumentation().getContext().getAssets()
.open("test_image.bmp");
...
}
}
And the file test_image.bmp is saved in assets directory, which is reasonable if you intend to use the asset for some testing related work - and its not part of ui resources. The technique is used in another context here: https://stackoverflow.com/a/4570206/1577626