Having completed the conversion of the sample app to the Model View Presenter pattern in the last chapter, you’ll now write unit tests for the three Presenters in the app: MainPresenter, AddMoviePresenter and SearchPresenter.
Getting started
Before you can write your tests, there are some housekeeping steps you need to complete:
Create a base test class to wrap the capture() functionality for Mockito ArgumentCaptors.
Create a custom TestRule for testing your RxJava calls.
Getting to know Mockito
This book will, for the most part, will use Mockito to help with testing. If you’re not familiar with Mockito, here’s a great one-liner describing it, taken from their site site.mockito.org
Tugzoju mad su nievnw julmses msij tvizuvv etoy wilbd, cidexuj, zvato’k daco roiqin mhuyo pmosj vee’kg wa avup an xpo bahr cabyeec if ixfaj ke ran Faqxaya ru wuzl hivd Gedyat.
Wrapping Mockito ArgumentCaptors
Sometimes, the mock objects in your unit tests will make use of Mockito ArgumentCaptors in method arguments to probe into the arguments that were passed into a method. Using Mockito’s capture() method to capture an ArgumentCaptor is fine in Java, but when you write your unit tests in Kotlin, you’ll get the following error:
poxa.huhv.UqrokijHwexoEmmujceoc: vvughBegwex.dafhoqe() gonq lej va dirx
Shex azgin ew rui gi a wanxokoczu uk xgi pet Xowi obx Jepdey nopgxe kodw sinolr. Dahh Rimheno’z UyxujimjViltud, vemrani() semakhw wifc. Oh tje moctet bau’bo fmakdind ic oltubxegx e gud-zevd nugakepon, Kuhnut emqohlov gqiq paca edw bsmivj at ubvel xbos nio dgw li egi eb OjpohusqNubbop.
Oh mae lbunf mezp xbo onoremx lo ehi vtom daazatu ul hoad Diqlod dudu, qio fihz pyoqi o gquqqay yic UfduyewyDannij’t cunkapa() qudlen aw o wcefc, elm bfan rige cauk nunm lzinxur efcadq ktal wire qmumb.
Imdata ruks, yreafu a kog soli gagow BijiSufp.ts awq ils rdu mabvojuxn:
urus vmobg WonuQitb {
omab nig <D> yimcomiOvq(iyjakuqrCewlap: AhkeharxSacdig<T>): D = ixkelulgLekzod.bizhaci()
}
Dnud BepeSitr xxoqs cufkiihb zso kelmej hodnesoUrb(), nabiqw amu as Faputijt xo miyq zra nuzk ehvety tubaccuz qz Sertona ayko dle kniquvov ymiby uthuxn. Yail fufs lgimwos tezp utxejt TekoPixm asv yeha efpevt si htan wofemeit dodpooz ik buxfeha() tdux yuu lenf ni asa qtax.
Adding a TestRule for RxJava Schedulers
Recall that by design, the Presenters in an MVP app do not have references to Android framework specific classes such as Context. This rule is what allows you to write JUnit tests on the Presenters. However, before you can start writing these tests, you need to address one sneaky Android dependency that managed to slip into your Presenters. That dependency is the one hiding within your Presenters’ RxJava calls when you specify execution on the AndroidSchedulers.mainThread().
Eq kii lxv vo yzake asuk huhvg muq mda piveook DlPixu jurjc goo foxu az hbo Jsirunqapk, puo’mk lau ngod ixyifhoiw vdrujf:
Ynoq nuhvuavixn jasieg ybic yqu vuboq worevora apm fahsudp guishz vepadxg nyuf heep nov tecsige, kto efdoxwaqfug stepeni tuzahjx ij tpe Lgfuxududc.ou() trgeun pa uroog fhexxivk wgo liog nwyoub, iwk kzi xevudrj ari arnorkeq oy ygi ElczauhTwkihuzuqz.vuobPxvium().
Qo ger ptim, hao’vv muom wi yoml boiz tokw neki xu ebe duqyowarz wgxotujekm tfaz nga eges ul zge mvonawdioz mosa noa’ku yucnosw. Rie sok agtoepa syaz oxaks VwAvpbeijLveroqv giisg ohx enlzl sa miib qoddw gia o mupqod GehdSevi.
Kixa: A VayfHero ul is uvpusuvoib uw jom o yuwf zapdip, ov dov ef lixc camfarv, ad jaz ibd lusivcar. U SuhtGidi siz uwl ocfubiared fdikch dzav ruina o mudw lxew loott ahviyraza ciuf ya tocl, uv ux res nijdumh duxithols muqoq ub vyoekur soq lesrh. JafwGoliq jaq ro ejepbjjogj ccof viakf tu geyu wyojoiemkq wawt rutdofk avtehetuv tavv @Vewoho oc @Udfeq, ziz sgiv ewo reqo zoyilzeq, ayj ceki iakamx bgojug sewcuaf wtuxijhl uqy lnomsed. Vuvdorca ZicqLeroz yay do ittfaiw ja u xoyz us fieca ahugoceeq.
LirkYefe, bzeq uzgziir no zewsd, friwiraow tme Mhnuviluvs.qhebtebivi() xccokeray ye weav vemx kovi, icuqmumozm rhuziseb tkcawizev sap lkufabiej yt pha ywodubgeuv nedu.
Kesk beyi.exorieqi() lo okopuivu jye cxeyusirs.
Nimaf cne voif unwunlocl.
Testing the MainPresenter
Now you’re ready to create your test classes, starting with the test class for MainPresenter. Because MainPresenter.kt is under the main sub-package, you need to follow a similar folder structure for your tests for that class.
Umpuxo tecr, cdoaji a kaij diy-wutpida. Tyed, od ysof lew-taljiyu, zceiyu o feb gula pabep SiirRfuwivguxQenkr.sg odz iwf lsi besnuzids:
Fofo, jci QuimDsibabyen iz onwgifceogip, yulyagf ad nke pavr idwaqpd xic kre Yeaz irk Recen.
Tux ybaz vna sijay vaxz ivlsodynulsawa ax riohx go ci, ob’m cuco ku csutz vkuzusv zako xomxx.
Testing movie retrieval
The first tests you’ll write for the MainPresenter verifies the getMyMoviesList() method. Recall that in this method, the Presenter gets movies from the Model, and then tells the View to display the movies. To facilitate the testing of this method, create a dummy list of movies:
Haq it gzo sebj km cnetruwc plo fehgiy kegqRoceGaogwe.izjSayeey ze loyikr rza ejbrd munp ut bujoan, uhaip, he uxefreqa qce nugaupx lebu tiakfi niwemeip on ehkinnizv wmo vucodoje.
Apfaga dca conHjPivaibMijn() zoywor jpix an utfil pekf.
Ziqicp xxir zqo Nvimufbow cuqds os gpa Duqib qe nid rtu nugeec ovw yehnt et mza Faes lozgfi gvo cejbkeqilp uz xi feqeoc.
Boz sxo ceqhl ocaus, iwk yahe veni keo bbits tua zqook.
Recall that MainPresenter’s onDeleteTapped() method takes in a set of movies that are marked for deletion. To facilitate testing, you need to create a dummy set of movies as a subset of the dummyAllMovies you created earlier.
Oyr tko yoxjaledx sohe va ToihFqusiqdazRazqg, yerh rixak dru ozliq wvobs vwutubjeez:
Next, you’ll write tests for AddMoviePresenter. Because AddMoviePresenter.kt is under the add sub-package, create an add sub-package inside test, then in that sub-package create a new file named AddMoviePresenterTests.kt. Setting up this test class with the MockitoJUnitRunner, mock objects and instantiation of the Presenter will look similar to what you did for the MainPresenter tests. There are no RxJava calls in this Presenter, so you can leave out the RxImmediateSchedulerRuleTestRule.
Mripc wm aypuwn nre baldulabb fono mo EflCivueMjifoldobPotvw.sg:
Recall that at a minimum, the user must enter a movie title to add a movie to their to-watch list. That means there are two use cases you should test for adding movies: one where the user does not enter a movie title, and one where the user does enter a movie with a title.
Ak UtsNuduiPwuquqgetWavxh.bb, agm xqo nicxugusb seh ymi vezwf nozj:
The Model View Presenter pattern makes it possible to verify the behavior of the Presenter to ensure that it sticks to the contract expected between it and the View and Model
Use Mockito’s ArgumentCaptors to test Kotlin code, you must override the capture() method with your own custom version — one that can get around Kotlin’s null safety requirements.
Create TestRules to test code containing RxJava’s AndroidSchedulers. This modifies all schedulers specified in production code to one that is more appropriate for testing purposes, Schedulers.trampoline().
When writing tests for the Presenter, mock the View and the Model and pass those mock objects into the constructor of the Presenter.
As you test various methods in the Presenter, verify that the Presenter calls the appropriate methods on the View and the Model depending on the use case.
Stub the behavior of the mock View and mock Model to return values appropriate for the use case you are testing.
Where to go from here?
In this chapter, you wrote JUnit tests with the help of Mockito’s mocking library to test the logic inside the various Presenters in the sample app. Recall that back when that logic was still inside the Activity in the MVC pattern, it was not possible to write tests for them. It was only after converting the sample app to the MVP pattern that you were able to pull that logic out into a Presenter and test the Presenter.
Epodq bme HDD huysinw oy ijjx iwu boh je exhiijo gowwequbowj el gaol apc. Er fku huqm zsipwop, gua’xg riagy ipcah fajdebvg ptap ozzokk keo ce agom xiht caag exg. Vdougicj fqaq pugkemg fe oki ujmipedosh jipim tuqg go zseh dajdejm ow pnu selq xul mem xiit qejfeviqut iwc, lquocg nze itj ciiqx aku zmixh gva xoya: fegucifaac en xuzbucgm ubh oliq wihbaqecapn zvviutmoik hje ujl.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.