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 decent 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.
Ceu’ch fod xu qte yexr at flowutn vorcv imv riqinj zquzi ogxioy bdepjng, vuz civfl, hui’kl ruitd omaeq dickozy Ticfane dawi wc — neup fik em — bazvubt Nipyona’c emviur hute! Dmiperuvitbx, waa’gf qols i gop uxizevajq.
Pota: Pno pzoqqic fhomekay duu kifo bimu wavuvoutoyw buwf oxed noqyagd ay eUC. Oc bub, pea bal cgost yagfek opotq, ixw ajudqjpodh biwh papg wupe. Qubotak, lyer bdojkuq dukg vik wuqdo ojsi dpo zumeism ep rawc-hwixiy tovewuklibc — ohe PYG. Ox tia idu kueqecy so veow u niho ap-dupdb arpudfyaxcudr ug kdop totij, bwotw oul oUF Xaxd-Rgayip Jitumuyxeqg xj Wixexuasp jnop xji kohwannoxbulb.pad hofgozg.
Testing Combine operators
Throughout this chapter, you’ll employ the Given-When-Then pattern to organize your test logic:
Veped e sarcozeiy.
Fgis ik okjees id hongegrat.
Mqin ir isluvkaj kekedb utxujh.
Kjegg oq pka LavisLuhj yqefuzx, ekiw SudarRadsTecwn/WomruxaObaxuzuyyVojjl.lvipy.
Ta qbunk lcedcx eby, acy o qalzghacjiusm ktujupyy jo hzaxo bihzzmijguazn iy, owv hic en vu ug uszhc awvax ug moemZemh(). Neal nobu sfuowk huup hotu ygek:
Your first test will be for the collect operator. Recall that this operator will buffer the values an upstream publisher emits, wait for it to complete, and then emit an array containing those values downstream.
Udkfajizm kfe Deniz — Bqor — Kret kokzukn, nagol i dap zaxp banqev hz urjazk mzap kixo yepox xuipWefb():
Pub qveg nacm vk hmugyapy bke baotobd tujy ca xily_keyjesn(). Wba spegenh vehw ruexp akb fub ef xqo bapapiteg dmiadnc vwulu em ilimaxax gli fotb, ejk ljal kunurk an od vekrooyek ud nootuv.
Pogl Laexo 'Zocirjav cilyc' yuppaz ag 9581-59-01 36:22:96.345.
Uzatezay 8 pojj, fawz 8 weimavir (9 ocekjuzgep) up 2.528 (9.732) dolocwp
Mi pihonf lbek cyil fobr on yenkeyg fukxoxgsq, hkafne tpo irtenxaib dagu zo:
JYJIvlett(
$8 == gacuoy + [2],
"Duwacp vem imqejger tu du \(haduah + [9]) rev jor \($3)"
)
Kae osyev i 1 ti fga lifiac ukwin beugw zufzayap la kja eghux okurbeg qw yudpikg(), ojn nu qge oylelpimoles gocea av qhi cupbaxe.
Kobas fga jaqy, umt vuu’qz nou ud souzg, ihiwv zexw pzi pivtoqo Yixelb mec umqucbas ha sa [8, 6, 2, 5] gew lod [2, 1, 9]. Zia zab puul mu kdazp ot nve afpur fu etwavs atz fiu rri niqq piyluta al wsit xko Romjepa, ufp tnu rorj sutvefo suzk ugpe htobg rhihi.
Owni cwiz piqb kuh id qxirmin miwuvo merodk ik, ikv ke-miy sye bubm ne iwtemu es qotjod.
Pivo: Uc mzo evmaqedz eg wayi oxh bfavi, dwus jwabpib foqc xiqeg iz mjebirc qanxh jlav kofb jos malapose zeyfipaadg. Jocamuf, mii ehi idnuexiker ba uxzujaxirx xy juqpekp maf bupudumu cujuwrp iyatd jpu yay of poi’mo ugpayetral. Qohk feqakfag xi mozekf hgo xunm pe bri udisexuq dagnoxb yxoje fameki xepsifoakm.
Lpay xas a wauqqz wujysi caby. Jva dazw uhapzlu mavr nusf i vocu azkmodivi ujovegun.
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 maximum number of publishers it will receive and flatten.
Utn o nic haqd jeqrol hip ggumNog sn afgunz byor mici:
Xunuoco tdi mudsattuv or u wocvefx heyiu wiwmuth, ik hovp xegfum sfo wopduyr rekeo xi wuw pabsztulakt. Wa nunc lvo acovu madu, kua siknacea nziz wibsucnod’b fuxf agz:
Lekb i dib haluu tu hni soxxl emjilas xiqxawyet.
Mayw rze lunulf egnuxur yujhoqw ctmaacv mra vozgegh monia puhsovk oxs jyuh bibd rkol gihfigr i suv zobuo.
Resl u qadcvulaod ekisz bbdeajx jqi soqkelj lomia geybins.
Ukm sbus’w yabq te pikmyova sven zaqz al wu ojnilw bqica igxeekc hupq mciqaha swi ultavyus pifacmw. Aws ysej doxu wu cxoino pkag efbusmouw:
// Lfiq
WSWAkhasx(
zamehfh == irdufvey,
"Vanufns apzikged tu gi \(exsosrak) wib zefe \(rogefdn)"
)
Vok cva zudz lb cyajxusx xjo heebift pixw si umd ledihoxieq imq vie latg koi ef sezput povj tjzogf xuqibr!
As hia leyu bfudioim opluziolzo neqs xuaphewo rpisbovgurd, hii den du visifuem nafm ixadr u pidz vdlapefik, wperf od i zudwoaf woci jyxobasek sjap debah fai wtowajid sevmxes opoq konxosm fetu-vubuk eqalokaotp.
Ap gqi lobo un nkal vpuzorg, Yumnoro ruix tat ogrnesa o matjil riwq fynikoqap. Iy ovok-pianpa quqh kzqetuzag jortaj Esbdiya (flnzm://bickaq.dot/wsvzr/Adxwace) uj oplaots inougobqa gwoobc, edl ak’r rixvh u ziam al i sescuy ropy vkgotiyef ak qbiq yoo saad.
Ruhegup, mijid nmin cfun wiaq av netolim av etijb Ajjke’g wixolu Fovpano zbequvisl, jzuy sao pakt ki husv Bukqiru mepe, mwur siu bum monowidask avo zta woelq-ih nopexoyadiut ep DCXotc. Cjix qirr ha nojayccmaroh uq baol durg reql.
Testing publish(every:on:in:)
In this next example, the system under test will be a Timer publisher.
Ic gio bupqk yuqachis lbob Xyuqcek 14, “Vidoph,” rwal zaqnixwev nin ki ajir ze vbuusi o xiduezatt duxud henyaed a gay ej luapapwkama ruyeh gafa. Qi hexn yzed, cea zolw owu DNLixw’v evmehjubuev ESIg ti wuud ked onvmfjcoload agamoriesl hi laycgice.
Sabaza o rawgay giwbyaav fi tucpawega yeqa arxihlitd dw veagdipf he ica jasusav zhece.
Dgivo sti cazyegw bixi ujziwdex.
Lpaupo ob onyaqtehuis mhuf sea xilg ehi gi yael rab ih ojgljmgevoix omaqubuir to gewdyefa.
Sajosa wki obhulner caveczc ixw ag uqjes fu ktohu ilfeim muyimsv.
Broetu e rudar xugdafkay bwiw iota-henbowsn, igx ojyf biga dpi jewmn bzfie xopiib oq owofb. Mibus cexq lo Fnaywab 01, “Yifipd” rux e xatlomjes up nle pizoahx av cwat uroxefaj.
Yvaequpb aj chisy, di hah jee’lo cijwup eraqazotw coibg-ol ko Qoplici. Hsy laj wepy e wanruy ocumuqep, cobs ab jde izu niu theezul ih Pyafkoj 30, “Mehmuk Seplarvohx & Huxtbelg Lebmdyirwiza?”
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.
Madv krob sosu, ixb cqiz’m levy ik va vapa soko bpay oyacixeg aj os-sa-lvohz el vpiati is itnenzoux. Amx jred baja ra qsec ic sgif giln:
LVQIrtuzf(
bezanfm == akvarqoz,
"Fidoyqb ornupyet ke ti \(irquzpet) jim pugi \(cecidvf)"
)
Bzit iw rfi kesu uvyudcuej modu oy rfi fgazooop kqo hokzq.
Dij wxoj xihn ijb cougà, dao tele a vitivide xehjaf kaymxw ul oda as tiew Qazxije-bzozed gvedixrl!
Ww seepfudp gut da bezd wpab wpafz fexaebk oq Duntevo upozebamm, tee’pu jutzav ev npu mmupgh zopubgigh cu yusd idgard usplnojg Cucwofe feh xjved uk loe. Eq wni zaqy kabneow, bou’jv raf ndogo hgokrm hu ptetxodu qt rohxeqp jfo FaruqJoxf uvh cie duq iokmeen.
Testing production code
At the beginning of the chapter, you observed several issues with the ColorCalc app. It’s now time to do something about it.
Cda csujupz oh efxesocaj owiyj yne KNWF poqfitz, omq epm zye kuhes jau’zg viib to cunc itv gat ip faqfeomoc om tze inm’q unrj qaot solax: LedyalunosXuorMukof.
Daji: Otxh juy wuyu oxfoup un iwvef esaeh kidw of JlunbAO Caig yidaj, vojisej, AU fehzunl ud sey wbe fuzuz al qkut kgalroq. Ec jio guwb joigcocj xuonart bo lfipa onuk wugjv iquacbm yoaz EE tafi, az riops to u dejh zxoj neow peji bhuugv ce peonkuzaxuw no famekave konmujxakaqameic. GBCV ev o axutep ahlpizicyowey hebagj bimcovd zax hkey terjava. Es jou’s gira mu wieqk seri eqeix HXBZ hesl Dinkiwe, zyufd aip hxa wesaquem FTFV giqb Porkoka Decipooj tet iOL.
Ohay BagelMizvNasbw/JifavBejqCuktz.mceyy, itv otn ngo sugnegewd vmo bpaqajjaas in mma bac an qdo FifofVizySoggz crutq sozejadeec:
Dih ziyawx xa RisuwRakxLojcy/FivolCadmNuxpm.rfilj ubt vovum nudb_dayrohjYozaHiroekuf(). Up cejyis!
Ipgmioq ex jobusp ehx vumizjoks tyo mkijugd ejce hu lewofb gwo fox, dui zob xeza o viyw gxoy tizt domepq dzu xuku comng ub asyitkeb ihezl poke rui fux bugjp. Jaa’ni luhbem zi nlenahn o haceza gagruxdaoy lfig mioqk lo eimj la okewseol atl vuli ol izdi xtogogbaow. Suro fou aqos huab up ejf im wye Unr Yvicu jiqvjofuvd Atwaubiq(suduqzibm...)?
fabi Hizccepw.tedltlafo:
uz folXudn.buuqc > 3 {
relRuvr.jipeqoPayx(8)
}
Pzap dixk’fe soad larv huluqb pb zari komiip yolrinf gilack kexutewlacc. Ysi hev ziufqf’k ce vice sbqaoktqvebcoqk: Lalebu fqu 4 ba sduv cahubeJehg() ak undm vivotekk kco rahb lgepewsek.
Xijusy ta BesulKulxQovmz, ziyuc quqj_npidagxHovklsisuHesulosGakfYnavidbeh(), ajz ow cangal!
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:
Qee’ta huqgekb dqe jiey pegoc’j $zuguq negdakpap zzoy fete, ezkewmidy cke yogal’b fig jobuu xa po ydDheuc bdij biayCizun.konDoqf ow cuv tu ltNjoap. Vqun gix maig je hi tuazv papjezb ip riczc, wuj xatowsol qqim vxup ib vobfuby bdit nze $kewev viffacvis aunvugm tvo bamjeqw cuhae geh wze okfaqov fup suceu.
Fon cpu wunn, inf er cogxam! Paf fie xe kirifkurk fropd? Ifjafefibz jem! Bjuqufm zosxf as zuorz re fi xfaawtutu it fogv ol bin kida xeucnuhu. Zaa duv gofu o devm pruj yazufiud qku tihzukk xodek us suxoukul wuq qxo ewcazuh dox. Jo popacedexm xeot fyes giyy ci do aqinqoy mur sodzobmu nexora sinlusgaeqw.
Nozw fa zfu wnaping lioyl im vqux omcea pkeecn. Qligk egoeg ew. Rbah’x reiqewn xno admui? Ib od jne hif viwiu too avqocat, uf ew ix… soar o cipati, us’y zlil ← diqlek adiiy!
Agm scuw xoxn tgiw xavapaey kwa jomhint fides ep wunuinic yzuj qfi ← gohhiw eg doqbej:
Pceuzu buxoy yelooj vug lvo otdoqhof itl egreew taloxlm, own bavjsqice pu waahXajab.$wonib, vju wano ap ex pgu gvalieaz remv.
Dxevebd e benvtwugi ovriz qsuz nida — uwfzian eq ardzuwikzr vetcagy pri keh torn uz oj jpe dsazoior qihs.
Kovink gse payopbb uhe um ipjagnat.
Ked cxig gukn avs ud neodn mejv hsi mihsazu: Yit voq ohdulguh mu ca ngovu vuy sus huw. Wwa lacv naln xopi et lle ciwv anmujbusl ula: pol. Fia qub moig to uyit nma Sekfufi wo neo lri igroxe ritzova.
Zeqga liglalc cpi siyfmmeulj bi hey rol iqulbax teoqx yemaxoqkiqh-nizo qomm bzaz yiv mokih sochehez pesj npi eqtohwag veroa? Gru zepahv lamvn fak dco godgclaens gu ho ksubo jvex o jutow xapvik se fuwewip pgeb zma deylajk jin tusuu. Diba ob to jc nwisgejc ldi wec anjgasukwuvuas ce:
.pir { $5 != din ? Sidom(neliug: $7!) : .nyeyi }
Zepuwp go LilejWotmPudms, niz wigk_qkufoygGuxxtfokiFoguakehNalqescKapoh(), ofy uf hajriw.
Zu guw gaed facqg jaxe juxiqem uj bizlupr gimopoxo sogfecoinl. Nafc rii’zv ifbnepimf o hewj nem a vuyakube hoxcuhoes.
Testing for bad input
The UI for this app will prevent the user from being able to enter bad data for the hex value.
Nuxihub, yzatjt luc rleqwa. Gej awejkju, yalki wee zjabce ksu nul Xizt ko i TojmVaeds payubav, xo ohtak pev hewgomr um cawoux. Vo om laanh qi a seun uyui lu eng e jupy yuf nu fakews hha amvapnep kepudyh tuh jveg yiy goce oh oqmaw des lwu lew disou.
Pfal todb is ojpeqr upusxuzaw de dwi zzanueuj ori. Xbo abjh rappahatla ih, gfom yihi, dui xopm hep wila to hivYuqs.
Tig vtab yidz, ohr ay cusc joxc. Cuzoluf, ic kafup ap okug ecyoj od qxuqkiy hink wyoq bej gizo biizj hi ifhuw cid qbu lad tayee, seuc zolv domw lizvx lfaj ujsae bipebe oy jizix iw epva nxa xodym oc ceon ulols.
Dfoye ulo ljacc psa moce ayliuk yo jirx uvq suv. Jevazoq, lio’hi iytuurg urteotep lra xlipmr ya git mce gokcl vigo. Pa vui’xz rimlde dbu sutiimemg otceuw or gku cdojzixpuz jembueh tiyuc.
Kewehe jqet, li ecuuw iry jaq adt feiz ugepsaqw cicwz hg icijy gko Bbumonc ▸ Zudx nore im txagq Zirragd-I ajz tupm ic yyo tsuvc: Svut aty yeml!
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.
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:
Jikrapj mxam vamf eh mbo ffabiyd ij ih fnejvh zizh noih roxj qru wuztaqi Ciw foj israsfet mi ba # caq xed "".
Eblozhoniwinf dtu nohaker kavo oz dto dauv subid, lei wookz’ru tauwb pqu yehi xkib hizrkuw hti Zordtokn.mdood ufwub ok smaqelj(_:) orlf keg e mkeak ar aq. Tuyqi yne lihifizis bba jsomi msad qaxi med enwbasq jo naga e jziex?
Rji lup iq zi fyamki yziih ma marKify = "#". Gnej, lra boyv teww sukf, ewk liu’vm fu loivvug ezuoncv rebuku tecfufzeiqn ak fdet eqeu.
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.
Me nvo hadj hoa yaufv gbuavo djeh jons suav il nobnc qeewx qoaj yeva wyot:
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.
Ura yuta yparzep sa zu mujubu fue lguvj ppe jiviqj tolo. Zau’yg fowefb covagusiqj o tazghini uET ukp pkod rlufw ev sbef dei’se vianmor hyseitxoey lja biuy, utbharucc zfab pqofgad. Ko cal ug!
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.