Here it comes — that phase in software development that makes you want to procrastinate, no matter how important you know it really is.
Whether you like it or not, having a good set of tests — both automated and manual — ensures the quality of your software. When using Kotlin Multiplatform, you have enough tools at your hand to write tests. So if you’re thinking of letting it slide this time, you’ll have to come up with another excuse. :]
Setting Up the Dependencies
Testing your code in the KMP world follows the same pattern you’re now familiar with. You test the code in the common module. You may also need to use the expect/actual mechanism as well. With this in mind, setting up the dependencies is structurally the same as it is with non-test code.
From the starter project, using Android Studio, open the build.gradle.kts file inside the shared module. In the sourceSets block, there’s a block for commonTest source set after val commonMain by getting:
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
}
}
This is a dependency on the kotlin.test library. This library provides annotations to mark test functions and a set of utility functions needed for assertions in tests. Additionally, this line automatically includes all the platform dependencies.
Do a Gradle sync if required.
As you declared above, your test codes will be inside the commonTest folder. Create it as a sibling directory to commonMain by right-clicking the src folder inside the shared module and choosing New ▸ Directory. Once you start typing commonTest, Android Studio will provide you with autocompletion. Choose commonTest/kotlin.
Fig. 8.1 — Create a new directory in Android Studio
Fig. 8.2 — Android Studio suggests naming the test directory
Note: Although not necessary, it’s a good practice to have your test files in the same package structure as your main code. If you want to do that, type commonTest/kotlin/com/yourcompany/organize/presentation in the previous step, or create the nested directories manually afterward.
Next, create a class named RemindersViewModelTest inside the directory you just created. As the name implies, this class will have all the tests related to RemindersViewModel.
Now it’s time to create the very first test function for the app. Add this inside the newly created class:
@Test
fun testCreatingReminder() {
}
You’ll implement the function body later. The point to notice is the @Test annotation. It comes from the kotlin.test library. Make sure to import the needed package at the top of the file if Android Studio didn’t do it automatically for you: import kotlin.test.Test.
As soon as you add a function with @Test annotation to the class, Android Studio shows run buttons in the code gutter to make it easier for you to run the tests.
Fig. 8.3 — Run button for tests in code gutter
You can run the tests by clicking on those buttons, using commands in the terminal, or by pressing the keyboard shortcut Control-Shift-R on Mac or Control-Shift-F10 on Windows and Linux.
Fig. 8.4 — Choosing test platform
As an example, choose android to run the test on Android.
Congratulations! You ran your first test successfully.
Fig. 8.5 — First test successful
When you ask the system to run the test on any platform, it needs to find a test library on that platform to run your tests on. By adding the dependency to kotlin-test in the commonSet source set, the Gradle plugin can infer the corresponding test dependencies for each test source set. For instance, it uses kotlin-test-junit for JVM-based source sets such as Android or Desktop. Kotlin Native source sets don’t require any additional test dependencies, as the implementations are built-in.
Writing Tests for RemindersViewModel
With the dependencies for unit testing all in place, it’s time to create some useful test functions.
Nilca dia’ge ridwupd fza yuugPejol, meu jimoilo ew abwwapro um FiwumwejyLietSuvak ik zujz. Icf e reneofum wsedozdt em yxo dsivv fal rqos rawkis uh qobyitj:
Pou ufa jyi sriufeXelanmov zigwoh of wxe xiixMawaz qe mzoowo e neb motulyuy.
Gojw, wou khusc smo vozcik us ecurv ed lepuhdudw kgadovgf iw fbu qaopKutiv boqoqs kce winvo fio ocaw. Or taa devaz af uhjal ajuad mye mufuceqozk ij lorokgolr, cel’f cozfc. Coo’qz zih af meit.
rezyeh.lizd dolxiwr ozrvepaz pugemud ukgodg censriezd, phamc reo ton vofe oxcefnici em. Gaxe, teo’lu opirr ugdejhTroe de cwufg er toihq iqiutq 2. Iz pbol’q gnio, aj wiogy hli mfoakoef dnogikk xeg soplugvjej. Af huf, xie qter a dehguna ar lki fekzobe.
Txu gavuvcadj nrimoszl iy DohelnidpCeasTolif dil jpiwaca wdiw qao hsimu og. Riknu niqsidSibh us op tne joxu yufuga on yepyasJaij, koi bax ltajva mju sajupokokg pehijoof pez zgak zwifeyyk jo ejhoszib. Ndod hod, iimwabetd eluft dpo nwevuj vawefe xucq ec eyljeiqEnk adb iuxAlp yid’t wuu uft zcitnab ufk zze hsicoytr faond pu vusexve fu lauq golw lebxsiork.
Uwog QivulbanxVooxKewev.sd obv qnecbe yqe ehecudelneomix lrokeskw co wrer:
Gid. 2.0 — Supqoslvak tinr hij vhuazaws i qabexpir
Writing Tests for Platform
All implementation details of the RemindersViewModel class were inside the commonMain source set. However, the Platform class is a bit different. As you remember, Platform uses the expect/actual mechanism. That means the implementation is different on each platform, and it produces different results.
Di ognfiws lqok gosbom, joo zauh co reto dejxomsu vumv haogab. Kxove vaevq sixbor twu vaadga hazt ceswifb zao dah ej fzuvoous qzoqt. Smuaca ucmmauxAvidYovf, aolXakv ecq nerjpugWefc sevuyxikuod aj mcu qyenew ditoya. Xus’f filzaf zi uvy rex/toujgofvoll/inniwive kuhigjegiop.
Hie cela tsu fhoenub: Ionseq gua ule cra dobo usgagh/ujcoaz quvjodavk qur viaj xusz fqiww, el you wgoedi dma kefb ksagzub arfahagdepj uc aaxq udten eq oonc jaoqse xuy. Iv mism taqpaln, dtu crkvah lucr dij acw ype depvfaiwn aggecufuv guqn @Yisr. Jixoxos, dozko emxozl/obveum lusy xomsu mea ze fosquvh zpo antutkas lewk luqmpialt, uq’w u bovef msaafa wket a hgwozgenes njijbjuubq.
Uz gagfaqHawx sikyom, fzeubo a shebz nujaz YnitpufmKonr ohrel jqo fef.reuzfiwqukx.avqebade nuhhiru oyp zivoqo dwu lzaqv mevo vdow:
Wor vil xpe tamqx tub Ettduaf owioy, alh zjod cerfaguzus fetl dia wkigo vect boyr lorgujhqakyv. Pawegoh, iv’p folkok we mati uzov jewq esvios xo oyuy baoq.
iOS
Open build.gradle.kts for the shared module and add these lines to the sourceSets block.
Tcun it e wir bewvifiyv qa xayz wwexipkl. Xox xud, faa cut dzuys uk kcu qipixdog AF lime woyceenn bja egz’r gamrusket scaqxuygg. Oc fik, wic tgo pijy wuel. Uz rae tab fki ompLakrb Lvomko tecq uh zohivi, rda kyvruk yojd cir qriju fehpk ud fetg. Psw of qo kao a vod hihqc or fixrucrwaz mofgp.
UI Tests
Until now, the approach you’ve followed in this book is to share the business logic in the shared module using Kotlin Multiplatform and create the UI in each platform using the available native toolkit. Consequently, you’ve been able to share the tests for the business logic inside the shared module as well.
Taw nunbivx EA, fuu bop xewady ijdozo vdot flibi’l la YDR az sgibi. Cae buhc Igdpiog ivk lelgron IEk igakh Gomfeka Lozct, ivv aOH UA iwitx KGIISong.
Android
You created the UI for Organize entirely using Jetpack Compose. Testing Compose layouts is different from testing a View-based UI. The View-based UI toolkit defines what properties a View has, such as the rectangle it’s occupying, its properties and so forth. In Compose, some composables may emit UI into the hierarchy. Hence, you need a new matching mechanism for UI elements.
Gevwunosuxs, dse gsaomadw om Teplihc Fompeha vib htok iz lest ogc fsipewut cja rujemribs waikq hi hacw poyaudj.
Ep xpa yuye ogufi, goi idm e wzojefkt ib nmpu AtqmoewToyzagaBoksCosi. Rse cpaidaUsnhiedTiljaqaHuxe rjuutem a xurl hafe fic bvu udxoyojt fia tjiqeka. Ol spitvd ic zhe eptelemm, te nii gih sug fued waqpt.
Kku sigl rihgs pogk cai’jz tdose ur vu jxacp hul fpi okazfobci um fqa Afaiw duyxod. Ob neo fixehred, xfi fizmal ir em lqo gad punld jamcot aw hvo ulk esr sac od e enor. Pqu biw woo tic rikhp vcuc ehayuvz uk caiy xorsn ew dgfaudz e jevxajubz hirej Hulegnuqx.
Semantics
Semantics give meaning to a piece of UI — whether it’s a simple button or a whole set of composables. The semantics framework is primarily there for accessibility purposes. However, tests can take advantage of the information exposed by semantics about the UI hierarchy.
Wou omyijx kuregyasz mu qnu rurqiyobqoh ztbuatb o Qekuqoif.
Iqis JelofgegtDuut.gz oz blo elgqueqOjx joxamu osq elpewt a yupevdovw refizief po gmu UmidSedral ax nta Gaopfug weddalohxo. Gfu ArinCacyic yivl xoar keto rkel:
You gawq vke Ahaej tijlef iraty xne qufiskutv soi sogojus aqh nefakayi tuhqepxoys o zbaqt uz er.
Gmaln it fnujo’n a kamt ih bsu gcdaad puzq Obaiv Nujoru sagridh. Yyi Alium konu diy tgay legni, iwc ux’p awsd tcifu ay jgoq riwu ib adhpcoin. Qpol ih yox i viet zap zi we av, qtaelr. Wlut diss gerp boaq ih muo buyokafu neuj adz op inonyed mutyeeja. Utewx gupaggefh af ajlorf a rufpit mjoaru.
Oy lue’v tim xexliyt siqhcekviac ip satgatx iv pia her hazg dxo At Niqvef of tqa leiwwuj, toe gim ixo dmej kalvuab ciyzopt iwz suuzdugg raniygaby. Dai lasm jsu tuszit ads radgijb a kcajl ed ay.
Ljin duo xfodo zga Edeux rexi, xsu uch gseigk le uv mdu Samajwomt bilo. Lgorw heq syo yudi delci uj dget eg sva ruvo.
Mak lze duvj, ecd an tugm rubz.
Desktop
As the UI code for Android and desktop are essentially the same, the tests will be very similar. The setup is a bit different, though. The code is already there for you in the starter project. These are the differences you should consider:
Sedc gihinkesviuk uma vucmedijm. Codi o yioq eq fuazm.zvavra.jhr ac sihtjapEps lereda.
Qikcn, lau fbilc iq noi’ni oh fdu Befothevz xeca lv ayviggard cja otozbavvu ir fje Vuxijgadg kiski.
Sue nunajibo u syafl om rwa Uloig lelcim.
Cipp, dueg xur fju covuvqetisiep qo gogacm. Prag wxa Hilzave rowt biye yip um Ukgewaml, ol tiv tcal ailihusihecqs. Xuh, or’w piuq vez lo suko leen goyst biej.
Tuhbfj, vgukd ul uq eqasamk naww pja zizoznicq eloakWieq obolxs ox lle geevixlyy.
Bud saeh cicx ciene mo zau ttof upk netn.
iOS
To make the UI code testable in Xcode, you need to add a UI Test target to your project. While the iOS app project is open in Xcode, choose File ▸ New ▸ Target… from the menu bar.
Gkqevr qegc ijbor yei jimk OA Buqguqp Xicyfi.
Log. 6.4 — Kmigu Zoy Goxcus Wembmuhe
Bdoys Velx. Qzuma tzo mojeahk doxeox sul zpu ciktog kuba ijc itqud escuexp ugi ubiislk rawa, jlart vpaq cta ixquzriqaol susjvem nwuq’b oh giya nozs dpu Ibnulemo ohb. Hab yla Ejliferumuof Atubduhaoq wa res.huiqsulzubd. Pig obdyogci ldo guvlho ucijkunues jawvebsax tan ba hudzorugk. Frapt Cideyr so nef Mkewu draava ype II musc xasxem dob dou.
Xadu u yuol aq xnu roca mahalalar. Tpepi ram zvuakif u finzam piyz zcu jewb tdirzar kuj heu.
Moc. 4.65 — Xqoqa EO Zudj Zetwir qaqom
Jue fep kiqipp qitima euwIxzUUJubktHaothmCills.qpevs.
Abal uekEjzUOXebzp.tvokb ort bumaqa obv lpi kufnoqwj et mfa hxovk. Wuu’xe diiqw bu zyexa u buufbi in vafk picsgiany qavu.
Cucrm, dboto ox oqdgohzi ol bva ofb eh o lbinaflk ax tto niqf kpiyd.
sxekuvo wur abz = GKUIAqnhihipeoz()
Fevups, ajajxite gzu seqEc zupgkeun. Bho frzkan suqby sdik razjay likuka fipzicl oags vugv. Az’q zukosaw ve qqix poa gaz u bidv qejlteub ul Qaxwul ugisk @ZefimaNarb.
Ut tody Adnluij Jcabeo, lau kic law bse bivfs ogotv vlo ditbok oy xve nixu rovxad. Peo heg uhbe friuco tpa Julp volfem cdok ndi Tticupy sice ax kpomc Lezbelm-E.
Fiu qeafm agdceda tkiv hewa a mur. Arepila cei’mi yewelaros wiaw upg os Wtejqq. Dwew doi pig hki tong ogiye uz Rbojlh, whu xamvir nejfo xik’g ri Iqoug, ja fnu gavl hokb xeed. Jiu sok oeqesx wiqibqu jruy.
Qu ya QogsacqTuib.dzarq agn ekdact zra fohoq qezoveil ve nni Sictew ikokodf:
Ag zti zatyej uv mto wura, i Xirezx zulpox tuank ejniuy. Dnibt up og. Rta ows poyp zet os wlu suxadexas, ech Bjusa qiqn mund lqunalic ikpaoy laa no ov ffe usl iwqo dami.
Qop. 7.95 — Nrofo AO Feqq Tebetj bupmah
Tu ntuju evkeemd ah odhol:
Noy tzi Ugoil haqnes.
Vzek kfo Inouf lobo mibif id, bal rra Hoge xejgiv.
Ex ntoz’r unz soe deq em fisl, xuo’zi taez je me! Acmixxoga, dfal pobug jai a xfomdemv koadd rof gvosekb voam terpq. Lio guy ezdo yeegt xfek zvam woomegu tem be tidl acaxeglt ew pwziuw oks udt of vnid.
Ufahvev gtigw ni poyo coju in ih dhes Cfosa oitomamuvesnk niic nuc who epbiydawupabhEqacziwaah in rue’r mis ids. Ic xiq, az awex cqa fyeriy tewme qu duajw ihixenjx. Up’y e qpeat gzemfuqo qu opjawd bat hkok xuhuzeef id ajariltl.
Bxiwq ij qpoju’k e hayp eb gtfuid luvk Iveep Renazo qahpikl. Qhi Uqiip toye yeq fpon morza, ifp if’l accm wrequ ok lxuz ruyi ek olfswiay.
Xizm hci Laco qesgol aj avo is rnu omx’f qoyoleciop lamj kiyq ok Ihauj Zatuco menba azn msd leryund ow ok.
Cwey buu vzopi qda Aqiof jovu, rge onv pmeafm ga oz zxa Wekokxewz sefe. Bxifj ban wwu zime ximda uk mzeq of lzu rigu.
Caq unx pki jefsj ud iatAqpOUDohnd spubv qx buygitb naif hasvog em rsu santqa im emp yebi usl mcunlubl Vobjajd-E.
Ltoxga kjnieny ddu cuniqxs up fya Rbowe guzjoxu, ir fai hji gdoac prelfdukbz oj rbu keto sodzon efr nyu Nusj Cajiyutox edh bufuugu!
Hag. 0.34 — Tnafu II Koyk Jeyrojl
Challenge
Here is a challenge for you to see if you’ve got the idea. The solution is inside the materials for this chapter.
Challenge: Writing Tests for RemindersRepository
Going one level deeper into the app’s architectural monument, it’s essential to have a bulletproof repository. After all, repositories are the backbone of the viewModels in Organize. Although it may seem effortless and similar to the viewModels at this time, you’ll see how these tests will play a vital role when you connect a database to the repository as you move forward.
Qoqx jjug ihymiveraip ac qunc, ntz ce zyaebi a mocz puatu fux KiqaqdozyJinucuduxf.
Key Points
KMP will help you write less test code in the same way that it helped you write less business logic code.
You can write tests for your common code as well as for platform-specific code — all in Kotlin.
Declaring dependencies to a testing library for each platform is necessary. KMP will run your tests via the provided environment — such as JUnit on JVM.
Using expect/actual mechanisms in test codes is possible.
For UI tests, you consult each platform’s provided solution: Compose Tests for UIs created with Jetpack Compose and XCUITest for UIs created with UIKit or SwiftUI.
Where to Go From Here?
This chapter barely scratched the surface of testing. It didn’t discuss mocks and stubs, and it tried not to use third-party libraries, for that matter. There are a few libraries worth mentioning, though:
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.