Writing Tests
Writing Tests
Now that your setUp() method is written, you are ready to write your tests. A test is a method in your
test class annotated with @Test.
Start by writing a test that asserts existing behavior in SoundViewModel: The getTitle() property is
connected to the Sound’s getName() property. Write a method that tests this.
Listing 21.10 Testing the title property (SoundViewModelTest.java)
@Before
public void setUp() throws Exception {
mBeatBox = mock(BeatBox.class);
mSound = new Sound("assetPath");
mSubject = new SoundViewModel(mBeatBox);
mSubject.setSound(mSound);
}
@Test
public void exposesSoundNameAsTitle() {
assertThat(mSubject.getTitle(), is(mSound.getName()));
}
Two methods will show up red: the assertThat(...) method and the is(...) method. Key
in Option+Return (Alt+Enter) on assertThat(...) and select Static import method..., then
MatcherAssert.assertThat(...) from hamcrest-core-1.3. Do the same for the is(...) method,
selecting Is.is from hamcrest-core-1.3.
This test uses the is(...) Hamcrest matcher with JUnit’s assertThat(...) method. The code reads almost
like a sentence: “Assert that subject’s get title method is the same value as sound’s get name method.”
If those two methods returned different values, the test would fail.
To run all your unit tests, right-click app/java/com.bignerdranch.android.beatbox (test) and
select Run 'Tests in 'beatbox''. A display will pop up (Figure 21.5).
Figure 21.5 Passing tests
By default, the test display only shows failing tests, since those are the only tests that are interesting.
So this output means that everything is A-OK – your tests ran, and they passed.
Testing object interactions
Now for the real work: building out the integration between SoundViewModel and your new
BeatBox.play(Sound) method. A common way to go about this is to write a test that shows what you
expect a new method to do before you have written the method. You are going to write a new method