1

How do I add unit or integration tests to and existing Android Studio project?

I've tried adding folders in Project View as well as creating tests through the context menu (right-click).

I can't get Android Studio to recognize the folder as test folders.

I've also tried:

macarus0
  • 11
  • 1

4 Answers4

1

I can't get Android Studio to recognize the folder as test folders.

Following below folder structure, you should be able to see all your test cases labeled as "test" when select your Project View as "Android"

|- src
  \-- androidTest // for android instrumentation tests
  \-- main        // your source code
  \-- test        // for unit tests

enter image description here

shizhen
  • 12,251
  • 9
  • 52
  • 88
0

Adding a test directory labeled 'androidTest' is only recognized as a test directory if you already have directory 'test' under your src/ directory.

This is as of Android 3.1.3.

macarus0
  • 11
  • 1
0

I had a similar issue, my Android TV had no 'androidTest' nor 'Test' directories, and I wanted to add some unit tests to the project.

What I did was to create an new Android project from scratch (regular app, not for TV), and I copied the test directory from the new project into my existing project (mantaining the folder structure that @shizhen mentioned above).

Finally I renamed the package folder's names and I got the ExampleUnitTest to run and work ok. After that, I could begin writing unit tests on my Android TV project.

Hope it Helps! It's probably not the best solution, but it works

Nahuel Roldan
  • 633
  • 8
  • 13
0

Although posted answers are pretty straight forward, you may also try this auto generation plugin. This will handle everything for you and more, it'll also try to auto write test cases.

Use Unit Test Architect

Although TDD should be the approach for writing tests, but there may be a lot of untested code already written many times in larger projects.

One day I got frustrated with writing test cases of existing, older codebase. Hence, I thought of auto generating all the unit test cases.

I have created an Open-source Gradle Plugin which can be used for the above task. It is already hosted on mavenCentral. I have used it to generate test cases for my projects. But it can be used in any gradle project, (android, java, kotlin, kotlin+java). It may be rough around the edges but it has done it's job well for me.

BuildScript Dependency:

classpath "io.github.orange-3:unit-test-architect:$PLUGIN_VERSION"