Chapter 21 Unit Testing and Audio Playback
on SoundViewModel called onButtonClicked() that calls BeatBox.play(Sound). Write a test method
that calls onButtonClicked().
Listing 21.11 Writing test for onButtonClicked()
(SoundViewModelTest.java)
@Test
public void exposesSoundNameAsTitle() {
assertThat(mSubject.getTitle(), is(mSound.getName()));
}
@Test
public void callsBeatBoxPlayOnButtonClicked() {
mSubject.onButtonClicked();
}
}
That method does not exist yet, so it shows up in red. Put your cursor over it and key in Option+Return
(Alt+Enter). Then select Create method 'onButtonClicked' and the method will be created for you.
Listing 21.12 Creating onButtonClicked() (SoundViewModel.java)
public void setSound(Sound sound) {
mSound = sound;
notifyChange();
}
public void onButtonClicked() {
}
}
For now, leave it empty and key in Command+Shift+T (Ctrl+Shift+T) to return to
SoundViewModelTest.
Your test calls the method, but it should also verify that the method does what you say it does: calls
BeatBox.play(Sound). Mockito can help you do this odd-sounding job. All Mockito mock objects
keep track of which of their methods have been called as well as what parameters were passed in for
each call. Mockito’s verify(Object) method can then check to see whether those methods were called
the way you expected them to be called.
Call verify(Object) to ensure that onButtonClicked() calls BeatBox.play(Sound) with the Sound
object you hooked up to your SoundViewModel.
Listing 21.13 Verifying that BeatBox.play(Sound) is called
(SoundViewModelTest.java)
assertThat(mSubject.getTitle(), is(mSound.getName()));
}
@Test
public void callsBeatBoxPlayOnButtonClicked() {
mSubject.onButtonClicked();
verify(mBeatBox).play(mSound);
}
}