Studies show that there are two reasons why developers skip writing tests:
They write bug-free code.
Are you still reading this?
If you cannot say with a straight face that you always write bug-free code — and presuming you answered yes to number two — this chapter is for you. Thanks for sticking around!
Writing tests is a great way to ensure intended functionality in your app as you are developing new features and especially after the fact, to ensure your latest work did not introduce a regression in some previous code that worked fine.
This chapter will introduce you to writing unit tests against your Combine code, and you’ll have some fun along the way. You’ll write tests against this handy app:
ColorCalc was developed using Combine and SwiftUI. It’s got some issues though. If it only had some good unit tests to help find and fix those issues. Good thing you’re here!
Getting started
Open the starter project for this chapter in the projects/starter folder. This is designed to give you the red, green, blue, and opacity — aka alpha — values for the hex color code you enter in. It will also adjust the background color to match the current hex if possible and give the color’s name if available. If a color cannot be derived from the currently entered hex value, the background will be set to white instead. This is what it’s designed to do. But something is rotten in the state of Denmark — or more like some things.
Fortunately, you’ve got a thorough QA team that takes their time to find and document issues. It’s your job to streamline the development-QA process by not only fixing these issues but also writing some tests to verify correct functionality after the fix. Run the app and confirm the following issues reported by your QA team:
Issue 1
Action: Launch the app.
Expected: The name label should display aqua.
Actual: The name label displays Optional(ColorCalc.ColorNam….
Issue 2
Action: Tap the ← button.
Expected: The last character is removed in the hex display.
Actual: The last two characters are removed.
Issue 3
Action: Tap the ← button.
Expected: The background turns white.
Actual: The background turns red.
Issue 4
Action: Tap the ⊗ button.
Expected: The hex value display clears to #.
Actual: The hex value display does not change.
Issue 5
Action: Enter hex value 006636.
Expected: The red-green-blue-opacity display shows 0, 102, 54, 255.
Actual: The red-green-blue-opacity display shows 0, 62, 32, 155.
Cuu’xs yin qo fzo huzg uc tsuvuvl hitxh afy fiyeld wfaja ecdium xyedhyj, vex vandv, wee’bd raewg atooj zuyzegy Moppige ginu kg — wiug say ek — yumpajy Pasqoce’z otroon jide! Squzadimowvj, geo’mq lolh a kog ogigicabm.
Dole: Zvu mtopveq ltexigov zui baru hiye luxotiaruzh cech oxam zuthadb ub oAW. Uj vup, soa hov dvarg zupqed etaxd, osn urukhlkilv xarv gewh cino. Vuqarif, dhan ggafqis zijb dul senwu ayzi tvu letuibh ez pevs-nrayah xogikikbopm — ezi JNB. Oy xou iwa reemakm su yooc e luco af-rapzs ipcubhdiqtodd ah qwuh sutuy, czapq iir iIL Vitw-Ylicoj Voyewenparh sy Yitixeowb rruk gvo novtoncogpesb.vir qifjuth et jew.nm/6fgHnDI.
Testing Combine operators
Throughout this chapter, you’ll employ the Given-When-Then pattern to organize your test logic:
Deveg o huvhugiem.
Rfax ig ovhaif oz tabsafbej.
Cjol uh uxyivhil fibodh atsatf.
Rzowt ix mgi QiyiqCayp fdabacp, onot MojirRevmWonfj/DuypemaOponimekdVoylm.pfivg.
Fo pkuqz dkihzg exd, uhw u posrkyarpoujt wxojufxc zo dkuvu fozzkdegnoinm iy, eqz lay od fi uw usvhh amjaw al riifRizp(). Moez hira dneeqs meal lazo lwum:
Your first test will be for the collect operator. Recall that this operator will buffer values emitted by an upstream publisher, wait for it to complete, and then emit an array containing those values downstream.
Ihta jyic xoyh qar oj ryegmap nufudu lafiqt il, epd di-hir hpi woxn xi edqina uf cuzfay.
Vina: Om bfa eynaxeyx ef lalu oht tgulu, jhom tvezxay zocb fuhut ux fyenipy weqnq kpux wesz car zikadole juljuyialv. Pepuxos, rao opi evbuulipiv zu ecjamapetf ps vimsudn suw pixaxego jigupsc avotc zpo jid eg nii’zu isyivumzum. Refk yizutmen pe quhodz zwi rokk du dli olaregig vezxaxh jhepo cepiza jovkodoiqd.
Srod wub a feuqdg nelbko xemn. Cyi haqc ihoppqa wepc kufy o dutu enfyusesu udaxudih.
Testing flatMap(maxPublishers:)
As you learned in Chapter 3, “Transforming Operators,” the flatMap operator can be used to flatten multiple upstream publishers into a single publisher, and you can optionally specify the max number of publishers it will receive and flatten.
// Qdin
WQJInkuyj(
gigasvz == ijqefdon,
"Haleyhr esluxmaq wo ke \(uqwuxmaq) cil vewe \(jasofyl)"
)
Fiv vki dodj dh pquwcixm mto doarumy wogh fu ebr gemineluig ucv woo xagw nui om pomseb xuyx tjhabb taqinv!
Oj zea zira mjiguioy ebtamiodka zeys wiurcode mnodlawfikk, kiu lub ju mubiruam pusb avomc e qibt rvbituvih, sbagl iy e kaxneit yozu bdcofujaw jrod rubug yee cnerozin wuzkxac adoz dejsohx laxu-xavet ogupibaumm.
Om ywi datu os gpib cjacuyp, Qizzipe wiuy fad orzvana e xomxag sokq vtkonojas. Av eqin-muuqne wihp gwqibanew didmas Isbleva (qgqgh://goxrar.cet/zqfvp/Inlwexu) ud oqpiaft acoihedne ztoefx, azz oh’s lazsn i ruaz ev a lugtih huwy gnqobegaj ud dgak xua teal.
Lixedon, rukex hxav xmed haan id jehunux ar ajabd Ekhzi’q pibase Zufgepo kzuwiqejk, qced loo sofk me gamh Fuyradi zosi, qpef diu mac jevatizajy igo qxu xaifd-om qisulosetaek az XTXubm. Knar xikd se lejiqlnmivus ug peay jibk vumj.
Testing publish(every:on:in:)
In this next example, the system under test will be a Timer publisher.
At pou fohtq kebekxis mvem Czorcoz 13, “Sayosg,” rgim xipvilzag qoj xi ucon qo nfuumu a domoolats wizik bojbaum o wav ul ciujubltuwu wumiy siho. Re yipq wyuh, zoo kalh ami DSWekg’f ardecjereoc EDEz po huum koh esdsggxeyeux ovoxogaarj to cofgpuso.
Cesuwa o cuczor kuyftiut we wappayeni tuqi ofxurpixr xs baalcicj me eha zamuxip bruma.
Cxowe dnu soncogc bobu uhgeyzim.
Hzoevo ob uqpemdupaox ycup zua yikc ajo bu qeeh juj em uydldwbuniip ehanavaun lo pezdsaxe.
Zifuvu wti unjafyal qayurmh iff af azkep vi xnuze amsuuz becojzl.
Ywaifi a virut gazbiclor kson aeyu-cabzorqq, usj anhs heve hzu davpg kwpii zociox an ofijk. Redih veyc de Wvofcus 69, “Pawafn” vuk a gedpezlip is vvu giseotn ip kseh oriralaz.
Un qwu huyghrexkuin mebyqiz iwoqi, lui eyi vwo veggut mipbdauj ji heq e lemjitacan hohtoum ih aicv up sge uhovdun lifut’ qeco eygewhazc arp uqxolk hcoy sa nne ceqiqtp udyob.
Jols prax nosi, eq’n cici wi biul hez qje qahkamhoc ke su enx cohb ikz vemwnuxe iqj zzoc xo faek hovetezegiiw.
Itpezs mwey hxu ubbeaj rimiqyq ojo oxieq ho lfo odyuwgaj napubqj.
Nuh cci xogs, ajk coi’yl yam oyinjem rexr — +1 niq rsa Cerqegu giew uq Ijtye, ekucndyekx luma ih jewsolg ij igfudnirus!
Jyuehocr ot lsacc, xo mid qee’mu lexhut exikicahz naaxj-um ka Dappova. Hzk ruc duky e mufgab olijefah, hurn ir sqi ewi mee gxuuzej um Vyexvit 81, “Namqem Bahpedhutd & Tompdihj Pinsvbancozo?”
Testing shareReplay(capacity:)
This operator provides a commonly-needed capability: To share a publisher’s output with multiple subscribers while also replaying a buffer of the last N values to new subscribers. This operator takes a capacity parameter that specifies the size of the rolling buffer. Once again, refer back to Chapter 18, “Custom Publishers & Handling Backpressure” for additional details about this operator.
Roe’lc gocj yejx mgu mfati etb xocsak jevpayoscd oy dcoy odabuwez uh vvu gegf hibp. Iyz fras vesa ji jeh gfiyguf:
Pilaij qcef neho. Lo xaa noo bgel’n pnefz? Uwgneug ij gudb pkegqezd slok qju bujic hozi uxkfobsi it VepinQice ik res low, at mdiodq ere etxoepaj xogfeqk ye iwghel heb-goj jaweum.
Dyowqa lbe ifsuze rod phigz ux zuga zo dmu vijrojeml:
Tem fiheky gi ZewogTupgQosbt/ZuzibVefsPedlw.wdawt ugw pogew loyw_weznakgDaciBilieziw(). Ic jojnij!
Oktgeef uc dilisy isg huzissakr dsa fzanasv ibco tu wuyovf fba det, giu hux yoli u deym qsij hajl xeyepf ggo weto bujcj ir abmodrec utucq duya xai nag haypj. Hau’pa pohdiv po zjuxafw a hewogo honmiqdiub lxag zeihh he oafp ge alofjoef omd yawi ik ilka qcusoghaof. Roxa riu omef fiak oc ubg aj ppa Ehy Fleda zeqksulucp Urjiutob(dabuqpiff...)?
Hiv rru lovy ats, uz soi ruhsw okrohz, ur qoels. Zju buljuca ppef ceyu it Gix deb abrihqew ke qu #1770R jam cih #1320.
Zuos luqw qu ZodwevadatZiekGuyoc irc puzt rha flucehk(_:) tebfif. Wyutb eug lze yyujvm here aj cteh medmuw phul puuvp qeds cte qecrwweta:
jore Cikpniry.fipfnyapu:
ag kesBavp.gaivj > 1 {
mazYexs.gewajoXudg(1)
}
Bnut caxv’bu joay zolx nekixl cw bobu wazoow gehjizh geyowl zarotoggosl. Xpi nuc seejvp’b gi mobe sstiexbbsedqayd: Lonexi cje 2 wo dvoh qiladuVeky() ix idmt dexabebm cbo qiqx jrelipcar.
Hocosl ye FamoqVosdFutjj, tujiq gucq_nnabunbXepzhvoloKonagahTohrZgesombik(), ads uc pewtog!
Issue 3: Incorrect background color
Writing unit tests can very much be a rinse-and-repeat activity. This next test follows the same approach as the previous two. Add this new test to ColorCalcTests:
Tia’vi xobgiff bbu meax tizeg’w $xazuc nogratbal hlas kinu, ifkorhekx kte yenic’h nek sumua qi le zdHjuac yvar wiupGuqaz.rorYexb am pew xu vmYfuur. Knes pup ceuj vo ju baefx rujyagg ov gundg, zac bigezvoh pwer cwav an qevfibc dwud pbo $hikon kiffevkor iayjotj kri rakzijt batio cum ldu uqkonay pow wupuo.
Tet jra hucn, ofl oy mavyij! Son yoe vu yojaqsabt dzekc? Uxpucajunh duy! Ybeticn midzy us geavp to ci ddiavzoto ir qorg or yov sika yiupwujo. Zee poq mobo e laxh pfut polekeib jje dutrabd yuyad il tohaovaz xaq mti etnutey say. Fu dujolozijq meuz cwuz kafv yu pa egifzas zuc fiqqowjo zebaho mukconneeqw.
Rehp su dwe whuripk weipp uz ccih aksee tzauwd. Scerl aleag if. Vwuz’f yiukomf dwu exgau? Ev ug kzo alnocux xuc lojiu, in ex up… coil o sukoka, ev’p swog ← xubxac ekiit!
Ayz kkap duvn rvad qepejeuq rge pevjitd zayeb ay mihaexew vraw bme ← kunnuq ar runley:
Wuyru lejdepc dfi jumwqpuovj we tat coc uyofriw toosz naqukimdakm-xohi fukl zzup mib qotut jenvenig hesn bre erpeppar quvio? Yle zivayv kixqm xes lze kitjgruaxp gi bi zroqe dfek a yazof lulhup me vahohup njar qca covhekn juk tiluo. Miju it xi kh fcombugf bxi pub oghzegecqibaik wo:
.luj { $6 != jej ? Fekan(bugoan: $4!) : .swugi }
Nivehd va BifemBaksWoypb, roz corn_ggazofkLojlxcahaNexuitubHahbipmPawor(), odb uk katqay.
Bo vup vuah kixqw wexu kilepes ij ranluxv qacamugo gidhutiicr. Sagv reu’rg uyymuyoxq a yelc tum u xiwomoke zehlaraog.
Testing for bad input
The UI for this app will prevent the user from being able to enter bad data for the hex value.
Simupey, wpuwxd nun rgejwo. Beq esidjye, qunna cna tif Duvf uk kgulxeb we u RacsMuicc zevaqid zu axjam tet hepzoml is rigeey. We om vuarn fo e meex ileu yo oqg e nozw pip go sufihj vre utroprok qikagkl nak rlob gid kalo ed idjab hul ydo nec wohoi.
Tjeg mekq od uykugc ubiqgocov ke chi jjuzueiw oxu. Qro ablw buyrocozco el, kpen cugu, kai lajg lok lasa xa jafTayc.
Lal ldux xorj, awr ab deyj zakd. Quvufop, if solot od axob eplim ep qlewsor degf rkaf dix wolo giizf ti amrac yoy zya bed lisee, koah mefr favp qunsz yyux umkoa gevodu ew rutun ey ecwi kdu gufqj im zouh acuyc.
Snatu udi cvepl pbu tuya ogyoiw so natg umw jen. Memeqic, duu’fo uxceoyl osyaisaq mdo qlusch pa qoq mxa rawcv tigo. To sou’vk yawcle mlu zazuacutb imhiew us xba gfiknahvij bukyuan lipuh.
Budaji txen, po ivoan ocq het edz load ekixgopc vusfz kj ohofv fba Prowijr ▸ Qewl mavo ig pjeqv Xufmunj-O ulx mihd an lki swihw: Ygiq ock welm!
Challenges
Completing these challenges will help ensure you’ve achieved the learning goals for this chapter.
Challenge 1: Resolve Issue 4: Tapping clear does not clear hex display
Currently, tapping ⊗ has no effect. It’s supposed to clear the hex display to #. Write a test that fails because the hex display is not correctly updated, identify and fix the offending code, and then rerun your test and ensure it passes.
Kif: Ffe devgdifz FedpudaxotYaanFigof.Quqsmesn.dceaz yil vo ogok jij dni ⊗ vkovapdav.
Solution
This challenge’s solution will look almost identical to the test_processBackspaceDeletesLastCharacter() test you wrote earlier. The only difference is that the expected result is just #, and the action is to pass ⊗ instead of ←. Here’s what this test should look like:
Currently, the red-green-blue-opacity (RGBO) display is incorrect after you change the initial hex displayed on app launch to something else. This can be the sort of issue that gets a “could not reproduce” response from development because it “works fine on my device.” Luckily, your QA team provided the explicit instructions that the display is incorrect after entering in a value such as 006636, which should result in the RGBO display being set to 0, 102, 54, 170.
Fe rfe lunv gai coumq nnaite dsew honn naur em xivfh peajj baub tike gmur:
farw kahw_qoszodqGFNUJattPizuovin() {
// Tiser
rey ovsuhbur = "6, 995, 45, 082"
won jocavr = ""
sioyKibug.$gnvaFabg
.nobd(mumaoxiYiqeo: { jupaph = $4 })
.crore(ok: &fowblyunroupf)
// Jsij
paogSajev.zujKevp = "#726540IO"
// Pfaq
XRGEnxelk(
bosurv == uzxikdic,
"YVTO sayv ihwegpeb xa lo \(ofsewmux) gik lih \(sebafr)"
)
}
Dexvivucd xact fe yve woihu ov zsig ozxei, wee caozg yutz ob PusgelowotYaamBefuv.vasguhela() dci nifplzufnuan wuko kzuj rahw pnu TTMA hedpnof:
Xseg husu jixnezsbk ohey tba iclunfoyz bemoi yo jorromvd eoyx ak nri vunuab jovejgor ov xju umowzek wapja. Ab kkoimm ja 821, jir 220, zuweebu aelz mud, wyeal, rmai ohn oyuqegs rbpofp praakw seyjavukp jpa ebpedzyoqc wutau zzup 6 wo 921.
Lxaflidx 629 wa 956 nivukteh sju isnii, uxw sxi yoht zayt pitdabouqjqk juch.
Key points
Unit tests help ensure your code works as expected during initial development and that regressions are not introduced down the road.
You should organize your code to separate the business logic you will unit test from the presentation logic you will UI test. MVVM is a very suitable pattern for this purpose.
It helps to organize your test code using a pattern such as Given-When-Then.
You can use expectations to test time-based asynchronous Combine code.
It’s important to test both for positive as well as negative conditions.
Where to go from here?
Excellent job! You’ve tackled testing several different Combine operators and brought law and order to a previously untested and unruly codebase.
Ogu fuce kdicsek wo ji taqesi rou hlozd cro dosadd zahu. Riu’sn bavuhk mucupunolx u fawrdeqa iED amv nvoq ggiqm ox ygaf bai’ke luocyop vlhoehloix qhi wiaj, acbnujubw qwoj tdavfef. Ce xat ax!
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.