Creating a Test Class

The most convenient way to write unit tests is within a testing framework. The framework makes it easier to write and run a suite of tests together and see their output in Android Studio.

JUnit is almost universally used as a testing framework on Android and has convenient integrations into Android Studio. Your first job is to create a class for your JUnit tests to live in. To do this, open up SoundViewModel.java and key in Command+Shift+T (Ctrl+Shift+T). Android Studio attempts to navigate to a test class associated with the class you are looking at. If there is no test class (as is the case here), you are given the option to create a new test class (Figure 21.2).

Figure 21.2  Trying to open a test class

Screenshot shows opening a test class.  The screen shows a popup menu on lines of code. The menu shows the following options: Choose Test for SoundViewModel (ID found), and Create New test. The second option is selected.

Choose Create New Test... to create the new test class. Select JUnit4 for your testing library and check the box marked setUp/@Before. Leave all the other fields as they are (Figure 21.3).

Figure 21.3  Creating a new test class

Screenshot shows Create Test window.

Click OK to continue to the next dialog.

The last step is to choose what kind of test class you will create. Tests in the androidTest folder are integration tests. Integration tests run on an Android device or emulator. The advantage of that is that you can test any behavior of your app at runtime. The downside is that since they must build and run an APK on a device, they take forever to run. (See the section called For the More Curious: Espresso and Integration Testing for more about integration tests.)

Tests in the test folder are unit tests. Unit tests are run on your local machine, without any of the Android runtime available. Leaving out that baggage makes them quick.

Unit tests are the smallest kind of test you can write: a test of one component by itself. They should not need your entire app or a device to run, and they should run quickly enough for you to run them repeatedly as you work. So choose the test folder for your test class (Figure 21.4) and click OK.

Figure 21.4  Selecting a destination directory

Screenshot shows Choose Destination Directory Window.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.114.125