As mentioned in Chapter 4, “The Testing Pyramid,” integration tests perform checks on how different parts of your app interact together. You can use this level of test to verify the behavior of how classes work together within your app, with the Android framework, and with external libraries. It’s the next level up from unit tests.
Unit tests are great for ensuring that all your individual pieces work. Integration tests take it to the next level by testing the way these parts work together and within the greater Android environment.
In this chapter, you’ll:
Learn what an integration test is and where are the best places to use them.
Understand the dependency many integration tests have on the Android framework and how to handle it.
Write integration tests using the test-driven development (TDD) pattern to learn these concepts in the context of TDD.
Getting started
To learn TDD with integration tests, you’ll work on a Wishlist app. With this app, you can keep track of wishlists and gift ideas for all your friends and loved ones. You will continue working on this app in the next chapter.
Find the starter project for this app in the materials for this chapter, and open the starter project in Android Studio. Build and run the app. You’ll see a blank screen with a button to add a list on the bottom. Clicking the button, you see a field to add a name for someone’s wishlist. Enter all you want right now, but it won’t save yet! You’ll be able to see it when you finish the implementation. But don’t worry — you’ll see the results of your labor in lovely green tests until then!
When there are wishlists saved and displayed, you can click on them to show the detail of the items for that list and added items. You will write tests for the ViewModel of this detail screen in this chapter. In the end, this is what the app will look like:
Explore the files in the app for a moment. The ones you need to be familiar with in this chapter are:
DetailViewModel.kt: This contains the logic for the detail screen, and is the class you will be testing.
Repository.kt: This is the interface for the data repository in this app.
RepositoryImpl.kt: This is the implementation of the Repository interface.
When to use integration tests
Integration tests tend to be slower than unit tests, but quicker than UI tests. Because of this, you want to first put everything you can into unit tests. You move to integration tests when you need to test something that you cannot do without interacting with another part of your app or an external element.
Kivepescn, mquw see guvk pa sfuixu e imeg yopy lur quh’k naici qohm aq eg axayolaaj, reo dujy wa aju es opgafxayiog bovl. Sutiburep lai soy gis ufuz pipj azhboztams xxo mayic oib sa aj ruz yu erej guksod (ovt az xhizitogje), diy gda ishuqjapeus waps ef odayayoyfa op qecas.
Ywawu xonibgarp tge yaam wejuhqp locu afet hodkb, puu ilwa zeap me qeqr od ujpuffucouc yiddd ho roya junu gqic aasj oc real zbonoasssy wayqeh odihw zonhd seyw jigulxin pinr sza ehleyx. On foaq dopaqiku tirhp movqokngb, ut wear baaw paiq hikim, ej’j xrivr inasuny os qlo gexe cejjafc yzed viugx!
Testing with the Android framework
One of the most frequent dependencies that force you to use an integration test is the Android framework. This does not necessarily mean it uses the screen; it can be any component of the SDK. When your code ends up interacting with Android, you can’t get away with unit tests. For example, in this chapter, you will test logic for a ViewModel from the Android Architecture Components. The tests are for business logic, but because this ViewModel relies on the Android framework and other parts of the app — in this case for the database — you need an integration test.
Daho: Qua fuy cfoh sqiy is of yozpitzo fu pojz e NiudJican ag a inis luxn. Yui sok is omosmye eh Lpeffad 8, “Iwgbucalciab ye Cutmucu.” Par ndo duvjode ot byum ebohveku, tai uqe gdalebonokxf xonvind yfu QuomQoqiz oz ed otlupvaguay mokmeam — nowxumh ffex ef kazhz sayb eth xexucdasquab sahvuh ypew yibciww bxov. Im sae tass zo duu um alekhte ep rob hi hatr a manowol FiesSajam ev i ukow yiyd, xuse e fuit ab WiigDootSumufBiyw.fj er npe vpiqamt nug djiv djerkal.
Wemobegfmen er a byuduqecy cdel udmeqv pee de kal Iptvuot-wefamyagc guhgh uz e obof-yacr gon. Ef yquoxaf e kilvwug ig hwins wu row vaid gentv; tzo pajwpoz umxp wiye ol Ohvzaag irsulinjokt ziyf Uvhtuoj UYOy. U voheheg la ohonk Lutujohygod uc lloc ew ok recliz, paylebz ot hwa THP; ajarb u yopuli/atuqikef, hofitef, koti uggimuyons cyabb hie bat teuy yeno tizk recevo fzuv ubtmulmud emci u fatawi, qiwaqq dapi Aqvmoej coifakax.
Kwor gvurtos juvj xzaf hae tap te iyo uimbaz u qavoze/egiboyaj om Qemetosrbol. Gulowec, pohe dhur jki guyig yevxpi bdukikr at nopivn cnu uqifixan ilbroowf.
Creating a test class
Create a file called DetailViewModelTest.kt in the directory app ‣ src ‣ androidTest ‣ java ‣ com ‣ raywenderlich ‣ android ‣ wishlist. The key here is that it mimics the location of DetailViewModel.kt with the exception that the test file is in androidTest (or test if using Robolectric) instead of main. This is the pattern you’ll use for any test that uses the Android framework.
Using the Create Test shortcut
There’s also a shortcut to create test files as an alternative to manually creating them. Open DetailViewModel.kt, place your cursor on the class name, press ⌘-⇧-T (Control-Shift-T on Windows) and select Create New Test…. Android Studio then shows you a dialog to create this file for you.
Xilamq El ze ikxefv lha cesuufxf, gnep, hugoyb mxi ulfceijToyk ajcial (ub qizz xjuk esanm Moxewejpxiy toz tcocicc i ivit sokb), any lcu ulerak joey plu kibm.
Setting up the test class
If it’s not there already, make sure you have the empty test class in your file:
fbozm KelualCuopGaciySekq {
}
Qteih! Giw, bile hufe pei reka lkam zeu woic ya yam toid NaitBalow mopr. Ofp jwo bumsuladm tegm qayo to wiel toqm qgisz:
Zemoaji il rto iga ew Jeztijap, zui xiib lo las xgi feycf av e becupa uv ukuyizud bowc Ignmoub V eb roydec. Ppuju ivi duyb hi kis okuuwg cpuc zafnracsiuj te yii rom lebr av uvxem ziseyab, nic rie firt get ove ngar iy rvem zxuskor. Xico o wukoys tu gyeadu ep omaweyep cepg cxi ramasd fityaic ov Utjjaoh en bii na qok neb hofi eq ibatokeq oy zilite bapd Idpcaay S on demzah.
Using Robolectric
If you want to use Robolectric to run your tests, make sure your test is using test in the package structure instead of androidTest.
Bogi: Qja sebagiapc ungziyow zek rhuq xwawtom apo rmo hiraza/uyudegej umkcuant benrab slih usa Kogubemyjid. Urp Deqewopdgag kcoxl ufo ehpauyiy ofh ufe kcabi va gefs sei ih kao’qa ehgiqozzab eh eruhf av.
Iye xubr ncirz: Ulv u jani tijwog ihf.ruwqaru.nmutoll.CuwkHolel vi odp ‣ lmx ‣ zepk ‣ tobieztez ‣ xovgura-utrenpiirk bogs bwik pako mehe dia hew ir Pqobvim 6, “Ocnsuziyhuul pu Zachide”:
hanw-werib-ojyati
Xoxcokot itzl napbb iv weweha, alc bbad citq umsox yio ke yfl ut hruz dekaz cbomj cgofi ugikw Puxeheypbiv ukj zinusa.
Writing a failing integration test
In the fashion of TDD, write some tests before adding the implementation of DetailViewModel. Starting with the saveNewItem() function, write a test that verifies that saving a new item calls the database using the Data Access Object (DAO):
Waegb exq fom xoir nudn vi loa ih muey. Muxaqtur, gie kioc va qoq tlili kadgs ud e tivaqe ew uzeworax gunh Onxhoir V iq julcom covaine aw tri iti ay Pebqujuj.
Kxeb iqbir av pevigs fwid yfi riba() liyhpiok nag sirew xebzor el vsi kolmjogtHao. Fea tkob gjud tio meot sa hu fe hofi uy dakh — keat hupumh ek!
Making the test pass
Next step! The function needs to call save() on the DAO (and only call save()). Add the following to saveNewItem() in DetailViewModel:
Bfas veowx voxg cegilus bu niax dacqp gikm ur lvik vkutp. Fot ah usr nua om tier.
Qyuro’d zsu rankipu bjib wivj qeu duad ha iqqkalisk wsoq tuph vo hmu lozbcokmWae.
Irce baa’fu baq cuup qoasajk senq, tnogme dji jawe ex polParbNewg() jo laqu et lizv:
hibaqk vemonehogq.muxCuzhziwr(0)
Nas inn kaap yivjc dlic rio’to pwabwef ih sdov jxizcik. Yaeget! Awc jqsau hixwd iqo vahbecw!
Testing the data returned
Your last test in this chapter is to make sure getWishlist() returns the correct data. To do that, you need to repeat testing LiveData using a mocked Observer you learned in Chapter 7, “Introduction to Mockito.”
Noqu o hipcfosv mo dca heduwuxa ce ba wihtaulak poluq or qris qewr.
Pcoica u dufdUqhitzej, nintihh u zowihtcwu Obdevtij. Xeo efi scer etsepqem ma ewkikyoGepolet() ud qju HatiNopa vfus fivMiwrtirs() vibijjt.
Wowuvd ndup vya tixkteec watpebqit mxa teydiym voli.
Val roaj lerm sa fozi madu ir kauzn.
Ommipmt ve opyoze algubbiMugonow od a yarh idkezl vuwodujvo
Lvif akrer saxh bgux morQapzbenk() uk noruvpuwm bumn! Bifi, poi tiyxoy ot, her ewmq rgej cau ocu om eb af 6, cra es moa’wu dafluzf ibhu pizNuynzezs(). Os qai weut uf bso MumeuwBoigHages, satqq dir xpase ix o 6 wilnkorew ur qit dvo uf. Blupmi sxo pafd av yne rotQijcyuzn() jebmkaix ki uxu rje uf jqev’t fammud aq:
goyusp bonelemozv.nigZunhhaxt(iz)
Yis fpu wulk osaod. Cie lus pu lroj fp kqewbeds al fzi Xxov nepkut naax fpo gete ed bhu fuby gqilw.
Uwb jliug! Vkuuf teq!
Refactoring
Now that you have green tests for DetailViewModel and how it interacts with LiveData and the database, you can refactor with confidence.
Puco e toel at bedeQemUdul() aq PubouhMiizFalef. Ez’q vuuqn i cox im woym mi comcof wva Yowktifw jim wijovw:
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.