Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 21  Unit Testing and Audio Playback


If you do that in a unit test, though, you create a problem: If BeatBox is broken, then tests you write in
SoundViewModel that use BeatBox might break, too. That is not what you want. SoundViewModel’s unit
tests should only fail when SoundViewModel is broken.


The solution is to use a mocked BeatBox. This mock object will be a subclass of BeatBox that has all
the same methods as BeatBox – but none of those methods will do anything. That way, your test of
SoundViewModel can verify that SoundViewModel itself is using BeatBox correctly, without depending
at all on how BeatBox works.


To create a mock object with Mockito, you call the mock(Class) static method, passing in the class
you want to mock. Create a mock of BeatBox and a field to store it in.


Listing 21.8  Creating mock BeatBox (SoundViewModelTest.java)


public class SoundViewModelTest {
private BeatBox mBeatBox;


@Before
public void setUp() throws Exception {
mBeatBox = mock(BeatBox.class);
}
}


The mock(Class) method will need to be imported, the same as a class reference. This method will
automatically create a mocked out version of BeatBox for you. Pretty slick.


Now that you have your mock dependency, you can finish creating SoundViewModel. Create your
SoundViewModel and a Sound for it to use. (Sound is a simple data object with no behavior to break, so
it is safe not to mock it.)


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


public class SoundViewModelTest {
private BeatBox mBeatBox;
private Sound mSound;
private SoundViewModel mSubject;


@Before
public void setUp() throws Exception {
mBeatBox = mock(BeatBox.class);
mSound = new Sound("assetPath");
mSubject = new SoundViewModel(mBeatBox);
mSubject.setSound(mSound);
}
}


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



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

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

Free download pdf