Importing Projects With Instrumentation Test From Eclipse into Android Studio

So recently I took the plunge and moved from Eclipse to Android Studio. It was relatively painless and by relatively I mean there were a few roadblocks and one of which I am going to discuss and guide you through here.

As this is not a guide on how to import your Eclipse project/module I will assume you’ve already done so. There are tons of guides out there that show you how to do just that. After you’ve sorted out any support library version mismatches or target SDK issues the last errors to sort out should be to do with JUnit in your InstrumentationTestCase class.

The new thing with Android Studio is when you create a new module it already create the androidTest directory at the same level as your main directory inside src. As we have imported the module you need to create the directory and packages yourself.

src > androidTest > java > the module package name

Inside this directory goes your test classes.

Now this is done lets sort those errors out. The errors will be along the lines of Cannot resolve import. This is easy to fix.

  1. Change the class extension from InstrumentationTestCase to AndroidTestCase. This is the Android Studio equivalent and allows you to get a handle on the context.
  2. Remove the @Before @After and @Test modifiers above the setUp(), tearDown() and test() methods and replace setUp() and tearDown()‘s modifiers with @Override.
  3. Now anywhere you used to get the context by getInstrumentation().getTargetContext() replace it with getContext().

That’s the actual test class file sorted out. If you were to now build that you would probably still get some errors regarding package names etc.

Go to your AndroidManifest.xml locations located in src > main. You will notice you still have the instrumentation test runner code in there. This is no longer required and causes problems. Obviously the following code will be different if you’re importing a project but here is what my AndroidManifest.xml file looked like after removing all the unnecessary code.

defaultConfig {
applicationId 'com.corecoders.corearchitecture'
minSdkVersion 8
targetSdkVersion 20

testApplicationId ‘com.corecoders.corearchitecture’
testInstrumentationRunner ‘android.test.InstrumentationTestRunner’

We are now ready to create our run configuration. To do so right click on your test class and select “Create Run Configurations”. Just select OK and then build and run your configuration and your test will be carried out.