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

(gtxtreme123) #1
Testing object interactions

The verify(Object) uses a fluent interface, much like the AlertDialog.Builder class you used
earlier in this book. It is an abbreviation for the following code:


verify(mBeatBox);
mBeatBox.play(mSound);


Calling verify(mBeatBox) says, “I am about to verify that a method was called on mBeatBox.” The
next method call after that is then interpreted as, “Verify that this method was called like this.” So your
call to verify(...) here means, “Verify that the play(...) method was called on mBeatBox with mSound as
a parameter.”


No such thing has happened, of course. SoundViewModel.onButtonClicked() is empty, so
mBeatBox.play(Sound) has not been called. This means that your test should fail. Because you are
writing the test first, that is a good thing – if your test does not fail at first, it must not be testing
anything.


Run your test to see it fail. You can follow the same steps from earlier, or key in Command+R (Ctrl+R)
to repeat the last “Run” command you performed. The result is shown in Figure 21.6.


Figure 21.6  Failing test output


The output says that your test expected a call to mBeatBox.play(Sound) but did not receive it:


Wanted but not invoked:
beatBox.play(
com.bignerdranch.android.beatbox.Sound@64cd705f
);
-> at ....callsBeatBoxPlayOnButtonClicked(SoundViewModelTest.java:28)
Actually, there were zero interactions with this mock.


Under the hood, verify(Object) made an assertion, just like assertThat(...) did. When that assertion
failed, it caused the test to fail and logged out this output describing what went wrong.


Now to fix your test. Implement onButtonClicked() to do what the test expects.


Listing 21.14  Implementing onButtonClicked() (SoundViewModel.java)


public void setSound(Sound sound) {
mSound = sound;
notifyChange();
}


public void onButtonClicked() {
mBeatBox.play(mSound);
}
}

Free download pdf