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

(gtxtreme123) #1

Setting Up Your Test


Figure 21.4  Selecting a destination directory


Setting Up Your Test


Now to build out your SoundViewModel test. Your template starts out with a single method called
setUp():


Listing 21.7  Your empty test class (SoundViewModelTest.java)


public class SoundViewModelTest {
@Before
public void setUp() throws Exception {


}
}


(You can find this class under the source set labeled “test” inside your app module.)


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 method marked @Before will be run once before each
test executes. By convention, most unit test classes have one method marked @Before named setUp().


Using mocked dependencies


Inside your setUp() method you will want to construct an instance of SoundViewModel to test. To
do that, you will need an instance of BeatBox, because SoundViewModel takes in a BeatBox as a
constructor argument.


In your app, you create an instance of BeatBox by... well, creating an instance of BeatBox:


SoundViewModel viewModel = new SoundViewModel(new BeatBox());

Free download pdf