Setting Up Your Test

Now to build out your SoundViewModel test. Android Studio has created a class file for you, called SoundViewModelTest.kt. (You can find this class under the source set labeled test inside your app module.) The template starts out with a single function called setUp():

    class SoundViewModelTest {

        @Before
        fun setUp() {
        }
    }

A test needs to do the same work for most objects: build an instance of the object to test and create any other objects that object depends on. Instead of writing this same code for every test, JUnit provides an annotation called @Before. Code written inside a function marked @Before will be run once before each test executes. By convention, most JUnit test classes have one function marked @Before named setUp().

Setting up the test subject

Inside your setUp() function, you will construct an instance of SoundViewModel to test. To do that, you need an instance of Sound, because SoundViewModel needs a sound object to know how to display a title.

Create your SoundViewModel and a Sound for it to use (Listing 20.7). Since Sound is a simple data object with no behavior to break, it is safe not to mock it.

Listing 20.7  Creating a SoundViewModel test subject (SoundViewModelTest.java)

class SoundViewModelTest {

    private lateinit var sound: Sound
    private lateinit var subject: SoundViewModel

    @Before
    fun setUp() {
        sound = Sound("assetPath")
        subject = SoundViewModel()
        subject.sound = sound
    }
}

Anywhere else in this book, you would have named your SoundViewModel soundViewModel. Here, though, you have named it subject. This is a convention we like to use in our tests at Big Nerd Ranch, for two reasons:

  • It makes it clear that subject is the object under test (and the other objects are not).

  • If any functions on SoundViewModel are ever moved to a different class (say, BeatBoxSoundViewModel), the test functions can be cut and pasted over without renaming soundViewModel to beatBoxSoundViewModel.

..................Content has been hidden....................

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