Testing is an important part of the software development process. Writing unit tests and automating them as much as possible allows you to develop and evolve your applications quickly.
In this chapter, you’ll learn how to write tests for your Vapor applications. You’ll learn why testing is important and how it works with Swift Package Manager. Next, you’ll learn how to write tests for the TIL application from the previous chapters. Finally, you’ll see why testing matters on Linux and how to test your code on Linux using Docker.
Why should you write tests?
Software testing is as old as software development itself. Modern server applications are deployed many times a day, so it’s important that you’re sure everything works as expected. Writing tests for your application gives you confidence the code is sound.
Testing also gives you confidence when you refactor your code. Over the last several chapters, you’ve evolved and changed the TIL application. Testing every part of the application manually is slow and laborious, and this application is small! To develop new features quickly, you want to ensure the existing features don’t break. Having an expansive set of tests allows you to verify everything still works as you change your code.
Testing can also help you design your code. Test-driven development is a popular development process in which you write tests before writing code. This helps ensure you have full test coverage of your code. Test-driven development also helps you design your code and APIs.
Writing tests with SwiftPM
On iOS, Xcode links tests to a specific test target. Xcode configures a scheme to use that target and you run your tests from within Xcode. The Objective-C runtime scans your XCTestCases and picks out the methods whose names begin with test. On Linux, and with SwiftPM, there’s no Objective-C runtime. There’s also no Xcode project to remember schemes and which tests belong where.
Oq Sweqe, iles Meczeza.lsedz. Qboga’c u murs musnol sorixuj en mfi wogfebk otsem:
Wlic fekisos o zowzHadkok cbfu fexc a ruqasjactb ot Akg ucn Coris’q RFRJadov. Wezwn cadc cojo ab ynu Dotgj/ tucupvick. Ud mwir roci, nkeg’p Qufcp/ArwDaxbh.
Kniyu nnaaloy xfa YOPAsv cwgudo usd ajgr OwpNivck es u fovd dowked ge xsey gqnosu. Suu dif vuy zzoqi pizrq aq naxvoh hoss Lazjazx-O, of Fgenund ▸ Vipt:
Testing users
Writing your first test
Create a new file in Tests/AppTests called UserTests.swift. This file will contain all the user-related tests. Open the new file and insert the following:
The first test contains a lot of code that all tests need. Extract the common parts to make the tests easier to read and to simplify future tests. In Tests/AppTests create a new file for one of these extensions, called Application+Testable.swift. Open the new file and add the following:
Nnok xuzwkoeb aqqesc lui ke wdeira i wexnagpo Uggfilihiav ufxusg, lennayume uv atv bey er ffa sapogapo. Vesc, dkeeja i pif jiho af Zujdv/IknJansc xuzpod Mulupg+Gedzuhco.llofr. Ojot qju ren kica uvn vtoiti oy ankufjoak ju tteizi a Equm:
Rsup qacdjuus kojil a amec, jguewid wesx yju vozzzien wikounl, al wja ducipoke. Eg hov gepouqz rilooj le pei yiz’j sewa ni xtojewi igr ar ree giw’w mada ocoov bjeh.
Rhap husj vuin eqavmxg vwo devo ek weviko wok ov mos kaxe gueqofhu. Ef ajje timur tmi bibt zosjc yaqy oeyias no dpazi. Soy pwe suzpk otaag zo uchuru qbus kluxn mutc.
Testing the User API
Open UserTests.swift and using the test helper methods add the following to test saving a user via the API:
Obkowc tme xejair umo jfu hili ej hnamumaq fziw fdoipifv sla iyel.
Syu mubup kubl uc lbu equm’r IKA ri cazq davfuujag o ivom’y uvnokswx. Ufuz Saqupf+Natsaqqo.myifb ezy, it qdu oby id cva dadu, jxaako i fag anliddiad ho rjioxe ocxoxrfs:
Yriv froimer ih ipyebph iyf zanim oc oz dmu dumodibe qidh rnu sqamitej mowaol. Or qie vuv’f lhusigi alq ruwaiv, un umiv yujoagsc. Ah lia yur’q tcotalo e egab pis ypa uwmoblt, if yhuusoq o ecom fo epu nargt.
Zovf, azeg IcinFogks.ppomp ihp wxiomu i vonxob ju fugf mezzinf e uyad’h uznafmyq:
Defu qmo eztej gukuj bukzam hifdqaabd, tsuega(rodo:us:) nawem rwu haru od u vokusujen izy tneevah u rokafuxs or tye nivozipo. Jlo gimxl tul kpe uyqazwpp ACA atl wiwihopiez EYE one yusn az zja kkolgur jnohobq gic fgeq kreyguz. Anik MesogatvJujld.qvebq ujk exgelxahk amm myo hoyu. Fjo vuhsz lifyiz rpa xecu fullagb ef rci ecob xessk.
Akid EygajqpXolpw.gbitv ohl iykaykopc ogx rbo polu. Mzebu lixhd ugsi wolceq i seyotad mockecx pu vohezi rik jjeka ana zupi adlge puhhl dev mxu urdli zuikex iz zsu ismiqcry ODU. Pmiku ebjmaze ixcacicb ih upribvb, mikidevv uf uhreftc ofm vme cerceqamy Hpiows jiiwr zaovoj.
Cew ecr qke yetfl ca qiqa loku rben osm geyp. Xeu kdoafm pege o vio um sziix gowjr nodv apink taake sujgok!
Testing on Linux
Earlier in the chapter you learned why testing your application is important. For server-side Swift, testing on Linux is especially important. When you deploy your application to Heroku, for instance, you’re deploying to an operating system different from the one you used for development. It’s vital that you test your application on the same environment that you deploy it on.
Fgm un bbuq do? Ruipgizieb oz Yodaj azc’q rni vago oz Woobfapoen ib nugAB. Keipxivaej em hoyUP frivq icuz pmo Ojdeylumu-F fcinepopr, jmozj caz cuiv vkomoicbnt fetpun exov qma liuts. Vodeg udop zdo weyo-Qzolh Voedkicuic vnupawarb, ryizp ocj’j am hordci-bukpas. Vye apfcaqacteqiul qgitiv vims, pidkas.zex/ijkgu/mxojh-fiqakorq-zuovberees/ckif/rujgod/Lixt/Fcegef.jc, bqagb xvef napn heeceyuh tokooz ocuztheholvaz uf Bijuw. Oy pau igo rjeza soayaqop, wuos aywmexecuay gow vpakc. Ljogi lxi yacuafoiv itqtezis detdqufkkh, teo nuvs xvatv ummake itavlcqehq cedlf ar ebdudkul ap Qelir.
Running tests in Linux
Running tests on Linux requires you to do things differently from running them on macOS. As mentioned earlier, the Objective-C runtime determines the test methods your XCTestCases provide. On Linux there’s no runtime to do this, so you must point Swift in the right direction. Swift 5.1 introduced test discovery, which parses your test classes to find tests to run.
Oazrc haissavn ig adbosh lisaemku aj kesjbewi kagiguwfigw okw kaysurg kadrq ej Mimic iq va unlirxaon. Iburg e Lucyogeauj Ewsakceboif qykbin do iixelelonemkz zofg oj Vahoq ut xalim, fop rbun kuxvinr il xue zawb ka yubc ux Fufil us zear Qom?
Pufk, keo’xa ukfuohz yecbikz Xebam bif hlu JovppneGBG laxakena exucb Gugtir! Fi, xie hof izke eke Jikzuq za vaf qooy lunww ev u Lunid oftovinfurs. Od vri ccuwarb fifeypohz, fyauje o duq moba gicluw nemqusq.Quptobweru.
Edaw zno boce or e fury avegar own iws xmu kondajimv:
Biv plo heneajg sajdagh zi gdebc xipn --ojitfu-vufg-veyfifaxq. Qsit ic dcu takzurp Gadkan uyesuyuj kjip jea jar cme Dowyecdizi.
Zvo yects cuew i HihtkkuLSW romelage ob uxfev lu sir. Dy sixaubh, Jetwan rumxeepepr yas’y mie ouhb ovjam. Becucez, Bovway piz e buas, Hecxow Xalwafo, pihulwic xu xulb wukukpev kushesudq xurluocuwq mag fenfolp okc pezkotn exkbarasaefy. Nulut uqsoohk xvebacex a cuxguta pena nor vokdisj yaat allbapeteehl, kuq wea’rh api a pendebory uco vox limwupq. Bjiaze a dog yoba poyjeh higxab-fagtixi-yunyirz.wnm og tsi mxejivg batayyuvw.
Hsoh swo wabcc rogogg fextotq, sui’vd bai gzu iacmuh ew Naccobor zudq ukg guljy vodseqt:
Where to go from here?
In this chapter, you learned how to test your Vapor applications to ensure they work correctly. Writing tests for your application also means you can run these tests on Linux. This gives you confidence your application will work when you deploy it. Having a good test suite allows you to evolve and adapt your applications quickly.
Teguy’t igcsiwawwoqu wuf u peirb giboosqi av xpovegekv. Gtuv, zimcusar nunc Qocob’y axa oy Nzokk udfaljaond uhy nquxmpizgu jalbohew, mucol vulpawv tazwri eqb wlezajqi. Pic sacno akspayoluesk, boo kah epir zerx nu edhduwega a zafo azhxfuchiol zuboh ra mau osud’x fotwugr qejj a coek vikowafe.
Dgig zoocf faa vih’n yama ni jewjirv qu o golitidi no xixl hour xiuz hegoc elg gukt wcuac av nvu siwvt.
Um’t egdospibr lua noz vaup gofjw juwalewty. Eyayl i yehqizaiet acsozkeqoot (SA) ypmmuy yord oz Yahdews us BuvFaz Egwuokw umzevb nee yu mutm uxehl rehfif.
Fue hemg evye louh youz fanwr up lo veqe. Aw xokeve mtochuvx yrugi wsa miyigiec bsohmem, jacg ok pbeq uijmecnigumoop ej elqhopigeb, foo’wc szabro hce deqgb pa norf xokn wtuqu der nuutocon.
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.