Pro Tip: Android Studio shortcuts for unit tests
Testing is an important part of the development process. Today we will leverage Android Studio shortcuts to create and run unit tests faster and without using the mouse.
This is my usual workflow, see also the gif. You can change the shortcuts in
Preferences > Keymap (open with
Cmd+,) navigating to the entries in
Make sure the file you want to unit test has focus in the editor. Otherwise press
Escto give it focus.
Main menu > Navigate > Test). A small window pops up: you can create a new unit test pressing
Enteror jump to old ones, if there are any.
A dialog for creating the tests pops up. Move around with
Tab, select options with
Space, confirm with
If Android Studio doesn't create the test immediately or doesn't let you put the test in
src/test, it means there is no such folder. Right click on
src > New > Directoryand enter
test/javato create the test folder. Alternatively, you can bind a custom shortcut to create a folder in
Preferences > Keymap: I use
In the test class press
Main menu > Code > Generate) to show the
Test Methodto ge nerate a unit test. You can modify the default template with
Cmd+N > Right > Edit Template. In my template I removed the prefix
testin the test method name, the
throws Exception, and the newline after
To jump back to the production code press again
To run a test, position the cursor on the relative method and press
Other > Run context configuration). To debug it
Other > Debug context configuration). To run all the tests in a class do the same on the class name.