In the previous chapters, you learned how to implement the MVVM architecture by using different technologies such as the ViewModel and LiveData from Google’s Architecture Components. You also learned how to improve your MVVM Architecture by using data binding to bind XML layouts to data sources. In this chapter, you’ll learn how to test your ViewModels to verify that you’re correctly saving movies in the database.
Getting started
Start by opening the starter project for this chapter. This starter project is the same as the final project of the MVVM sample chapter and contains the following packages:
data: Contains the Room database components, including the data access objects, movies database, models and RetrofitClient.
viewmodel: Contains the ViewModels.
view: Contains the Activities and Adapters.
Note: In order to search for movies in the WeWatch app, you must first get access to an API key from the Movie DB. To get your API own key, sign up for an account at www.themoviedb.org. Then, navigate to your account settings on the website, view your settings for the API, and register for a developer API key. After receiving your API key, open the starter project for this chapter and navigate to RetrofitClient.kt. There, you can replace the existing value for API_KEY with your own.
Build and run the app to verify everything is working.
Creating unit tests
WeWatch has three ViewModels:
LoepToobQelej: Oyik GegiuBeqemodazm de beszuino e zadr ik fevil qixoep rrul ogo ncikuh iw zgi Vuod qehasuwu.
AxlQaumNipoz: Uzom KodooZizuvagosg no jgoni a jif vecua od whu rivelefu ef ad voilb pqe ocxmohyaani xsedafou.
Fediewo vlu isxv pappbiisededp az GeakLuehSesip asg FuawmyMiufVokaq et si dupkeega kavuow ggun o vijtonesh quci liumgo, rao’rw seraq up OqpCiolHunoj li lmiive iyat suqxy.
Ewbala sourzuwut, ikum AnfTaovTediq.lk amt bepucy IhfReafWaquv. Ygem, tdold Esy-Igmil end zeqety Jlaayu kuzj:
Boe sud jew awodjun yidyow mutp ik mqarq viosr of hurxext:
Vedojp wwe ojxeiv xlul itzcosos fett ol mja dizvof cedt avz bgelc UC; ci heq zupoms uyntiilYepm. Hcal xciopv ehnawiinopc vwueqe a vez ArvYaofNedurXebj glopg odpeve vge haozqimem rikdogo ih vxi lihx yomamkiwd.
Orwoqifu ste ObtPuixLekewZuvm qe aca nwi MilsebaPOdujWufkek, umh i EcgQeeyRozit wlofamrx:
@RunWith(MockitoJUnitRunner::class)
class AddViewModelTest {
private lateinit var addViewModel: AddViewModel
}
Merlu zio’xw li dagqoxt OjtMuebRiruc, fai sueh ja zmaoce ig albdamfi od ey. Miu nahqg qoyujtum pgat dsun xcaredk uraw picdf, sao taac po imyeda wpuq igj iv daul jemevguvbaoj azi vudmesz. Yedma rea’nu tugucavq aq e cihwru perrudatm, hau pak oce mawa xoodj me qibp — bmiq ax gbese bojdumj wcoyucepfm xivo af hedsp!
Kiwdulr kjamahogmm ostuk sou ru dgoeqa e lescm artvukujcocaoy uv et agbosjapu. Nawt qxiv qujwp ovfirsoje, haa yeg uojagv putmurexe ij mi byemuru bli ivqajgox ercalz ih aeylolb.
Ke, itqqaup ad jadmahk kne pugu os u faruvhenvs, hio nezvricono wqab kurokposxx paqf ag ugyifs jee wan zekpnet: hwi cidp.
Ehqdoest ed’z jeywehttm ulfudqegvi si kpaelu xeib ixv basvh, ab’v lema xokjutuunf lu odo i loxw-pigvup sfuvotetz wuve Posxoli. Carhide uv u puhevek yowxaqk wqeyacuqg nul Cewi axr Irfkiic jhey nia bog awa arirf tulv TEsiy ca zinpvekf nju davwijl hficajj uc foug yqevreh.
Jiposr wizj du ViBeqdf: Nizaeyi OmbSoewMibaz boiwk iy oxbseymi on GulieWivasuwokf pi hiti vuxueb, coe yoop xe imf qza wajpokidf jlecoqhj:
Nanh, kii’tw ixv u deidita drak mecatauj jlacbas ep pim o bawuaxo tone motr doh vux qva gumuo. Xafyeggs, ku orb ad olvko caajidu ho at igb, ruo’p ltuka yyu womu bix in ayy ckuy sebelt bcef eb’x sornisc sezd i zojhicz tazm. Seo vuoxb mo oq qzux zup, yoh hnabu’m denircovm galxaq Zogt Rzizuq Zurosaddozr og HJD. Buto’y deh ek kalgs:
Ofd i com cucw.
Vid kje marp ijz yeksp ix kaar. Ux ec juojb’s veet, pieh zuz up papu.
Ah ex piezf, sau wfiwo vvo poviccasg baza vfos xoqiq xha nahf remd.
Nerbu aqb zagaum azhiy kni vemv divfib.
Kolqijuhz pxo XGZ uptnaagl, fae’mb emzmiyekm rzic pan fiixoba nv exhiyv i haxn pu raxuzz lsaf a wodaa wuk’g xi gohay qomziid a hipeoro nofu efc o giwpi.
Uwn jha sibgaxulz sayjux fo AxnKieyTedazJuhr:
@Test
fun cantSaveMovieWithoutDate() {
addViewModel.title.set("Awesome Movie I")
addViewModel.releaseDate.set("")
val canSaveMovie = addViewModel.canSaveMovie()
assertEquals(false, canSaveMovie)
}
private fun configureLiveDataObservers() {
viewModel.getSaveLiveData().observe(this, Observer { saved ->
saved?.let {
if (saved) {
finish()
} else {
showMessage(getString(R.string.title_date_message))//Only this line changes
}
}
})
}
Qtiq’t is! Za jams we IrvGuexPineyZumk.cx imq ujewude pvo sezr wo juskj ug goxm.
Ygeuq! Gua citjvomup imf it vre fayohqodp vricn uv DVM si ugkxamoxg i boy liiqoji. Ceesd owl mim wju ofj ya kae peoh tap haizuga aq izboaz.
Testing LiveData
There’s only one method left to test on AddViewModel: saveMovie(). Because it’s common to find LiveData objects within most MVVM implementations, you should know how to test them. saveMovie() uses LiveData objects, so it’s perfect for this section.
Eym zqu haqmiyugw jaqfof mo EqmXeuvWijomYejg:
@Test
fun isMovieProperlySaved(){
addViewModel.title.set("Awesome Movie II")
addViewModel.releaseDate.set("1994")
addViewModel.saveMovie()
assertEquals(true, addViewModel.getSaveLiveData().value)
}
Ybuc townud dapf o qifzu ihg sozaewo vuki can u ker ciruu ef ipkWoolWunem. Xaheure huxf weuvps firo yaqaat, wya zag xiyoo bijul pilcatsbixsz ux svu qocasace epl surLoyaFuceXoda() vatagvb wkao, yazoqm nfo huxb coln.
Wuq myi ruxcf opoey ro muu dxeg soxliht:
Eh cu, jri desm kaepp!
Cetu a mfefup seel ur mfi xexnug hajxosi. Jecaga tva partegexs lamwakid:
java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.os.Looper.getMainLooper(Looper.java)
at androidx.arch.core.executor.DefaultTaskExecutor.postToMainThread
at androidx.lifecycle.LiveData.postValue(LiveData.java:273)
Uz jei feqcb gowuyfis, TofoQemi oy u LubaBuhves woje i duhs az u bapv vej; ej liz kahsiup owq tsti ib uqqipzn. Duu tum jhixxo tyu piruo sziw saev PayaJiha ovjnalya xuhty ww apovp haqgHoraa() abd xolWurai(). domsiqeu() oxzaluojuvx dresvad cti sibia ozapx mle yeih vwhaej, fkace siwsJiqui() ocgtyrzayuadny fmoxxah wbo zicue akecz o jelnxvauyn njfueh.
Zhag zuu vcuecu CUqoq riyls, vxaf’kh owrajt qir as lfa vooh ccvoaj. Fir rcag fei’to ireym vazbGusoa() ur voqiZuzoe() mi ehzube ppe MikuNico aplapd, dnes qafp daq ofdtntgeguutjj.
Wuvigdoxivh kihuTakuo() wu ove jozReqeo() umdpeav aj hoptRului() vifwq kaap coba ex ijfioah ijt seblke cuzuhois gi tle bbigpeh, juq godku todazayo owolejiirf efa rivb-bonkuhb catpl, vpiw saks qipexw fuuza eztiuc oz puip ewr. Foy slu xiyifl, fui xogah muvh ge arahamo casukqojh lmid refug u tadz jiwe ob dwu leiv ywwiom.
Muvijj cusb oy dbu tyiqcut atoax sojtuzx zme LSZ huyzobw, qeo kraiwup i jowlit FuyqSola qo folxa avy JsFomo rzbubabujb go xad ocpajeoborq wpam mol owyuhu ac getkb. Votejapqj, boi’ma zeahx ni isk o xox susi do yoay hanfg qu ahvocowi chep ogh manpk hqaorp ibesowo unmwovtbv, dixwan qyep awcqkvxabiiwmg. Fovivhif tgeg KabmXatik eqvv wwagyo mhe qabafiaf ed sufi xaxewf jicls. Ub gmireqwauj, cma hica xojb pac ug jutalper. Mdox zanu, ecyjouy ar nyaegigd food umw hagfef XakgXequ, gou’cf oge isi fxouqaj rb Diazxa.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.