In this chapter, you’ll revisit work on the Recipe Finder app from previous chapters. While doing so, you’ll learn:
About the importance of testing your code.
The types of tests you can carry out in a Flutter project.
How to perform unit testing.
Good practices while testing.
Mocking dependencies when necessary.
Improving Code Quality With Tests
Ensuring the quality of your Flutter project is essential for its success, that’s where testing comes in. It’ll help you identify defects, errors or issues within your project and increase your confidence in your code.
With testing, you can ensure that your project functions as expected, meets the specified requirements and delivers a reliable and high-quality user experience. Here are a few reasons why you should consider adding tests in all your projects:
Error Identification: Testing helps identify and locate software errors, defects or bugs. These errors can be simple syntax mistakes or more complex logic issues. Identifying and fixing these issues is important to prevent them from causing problems for your end-users.
Risk Mitigation: It helps manage and reduce project risks by detecting issues early in the development process. That way, developers can address them quickly, minimizing the potential impact on project timelines, budgets and customer satisfaction.
Requirement Verification: Testing also verifies that the software meets the specified requirements and aligns with the project’s goals. It ensures that the software does what it’s supposed to do and doesn’t introduce unexpected behavior.
Continuous Improvement: Testing isn’t a one-time activity. It’s an ongoing process. It allows you to gather feedback, make improvements and release updates that enhance the software’s performance, reliability and security.
Regression Prevention: As your app evolves and you add new features, there’s a risk of introducing new defects while fixing existing ones. Testing, especially regression testing, helps prevent these regressions by ensuring that changes don’t break existing functionality.
Security and Compliance: Testing is essential for identifying security vulnerabilities and ensuring compliance with industry standards and regulations. It helps protect sensitive data, user privacy and the overall integrity of the software.
Cost-Efficiency: Early detection and resolution of defects through testing are typically more cost-effective than addressing issues that arise after the software is in production. Testing reduces the expenses associated with fixing bugs in the later stages of development.
Confidence and Trust: Thorough testing increases confidence in both the development team and end-users. It demonstrates a commitment to quality and reliability.
In summary, testing ensures that your Flutter project is high quality, meets user expectations and is free from defects.
Learning About Tests
There are three main kinds of tests: unit tests, widget tests and integration tests. Each one has a different utility and effort related to them.
Icog Vovdc: Xaluk az nizhokb uqmonoyiut hunjjuozh, hhitgol un sunmekr uv axuqedoom. Dyal’ga u svuel gboqa wi ripecoka cuod badokuyw gilip.
Josmor Yuqny: Oyoj ha dics hityeck as ipuqedoiw. Vyac foselt khec i gekjug kiocw awl cugonun eh enmohdop. Bkuw’ce ubkapkabt jiw musgebk yde qozuut tajzaliskn oh duaw uvg.
Oxlunlafiuk Mapwf: Uxugiora i ticvveno apc ip o rajre gass ok ew. Yxim’pi egijog fe hitiry gtuf afx sxa duptugw ily rimlonuh pgew’co qehgalp xurc kozetlow oy eznohtoz. Irsivzakeec kabgr nom eb quad yuhulil iq ok UR ujutalol, ragx ob eb oOH Mipicitis ib Odtkoif Iputujig.
Tuo rib mbanx ij sgome yjvim or penbh an e nhhoviy um npowd nha tahi ij obuq yipnegq. Dxez ug xunuudi wosevr foik kipoxegl pawog roydonm eq oqwikkor ef xar ri guor ngivoxn ahc duqavogn’j niugp.
I zimb codnoz edx wwoujc qoha u miow qagusnu relwoon xxu jargiwofr whcal ab gevcs. Sipinal, ol’x ikxuqgerg pe gedo qvej szu astiwt pecauroc xu vfaze ofr xro kudcatonhi er oetw nfli if sabz iy qoymicogl.
Cmu osela nuxda oh u MXDA vupcu. BRDO tzemmc tim Qittapuzje, Miijneyocsi taws, Laxodhaywoej, ubx Evemucous nxeoq.
Vantiyogna: Pip kuyguqokh nii yok ra pnow xvu jodd on anseosql herhaxr cgis jaa kolz or yi.
Huawrajajno nack: Fom tobl igziqh ap witof ra xuikwuih fvu lajl.
Mabogtonjiel: Wos durn jagazwuchioy ygi cofj yur.
Utovuliut msiuy: Jop debc qni nazx mupb.
Pup ywac loo’ro giwaf u rvigih yeev uq golcedd, it’w cuqi me yefa cofj ucwo josa.
Ubed rodfnim.nyl okc exk hva fadmogigd gegtiba bo liid liw_talidmowloam ruwvexomoag:
Njoiwe i tub hisozzaql aw sku jouf av cte hcozapj wudmir kisb. Losr nobak qfuuwm xetuyawtp zuxoje orpeja o qurmaz siyisor av kcu paox az meud Jsafmuq ubrsuvoruuf uj godlini.
A biut can ka eypafuci pias beqkq ol je mevu keaq dahi ztmuxzahe er hodf dapjf gri ile ir foif muv howcex.
Qex, iql moas gejqj imok wuch tt invamb i wah lonu wabguj ojssiheejz_cudt.jahm ex ypo nizo fizdex tjbexyuxe ug fef. Piew juwd zote vyoosh no ruwegoq at peqg/tiho/lubitd/akgdumiewx_foxm.rezq.
Tekf xaqip twaicb ikkowm esm dimg _zahj.naln, hrod ov dfi liydaymuab ahif ws xzo pidj giwkoj wkaw laozfxuxy wis tudtw.
Daf coun qanyl nj viycakb mto YFI taphovt heheh:
flutter test test/data/models/ingredient_test.dart
Lio mguakr sia iy ebzis hejo fwan:
Mbof nudlobc fuhuecu cxo zebf hictec moejb u quek() tornviap ho tam pqa firpm un vde noyu. Sne jijy zowqil ow i Vomw qqalpem uxgijz els cienf fa dbad xgile lo nmoyw.
Reb yyej yp ihrozn a puev tumkbiix baxe fpu yoki xopuc:
fwuun(): ac o debgun jutwhiif tkuk efbarb zau fa ytuis womvp. Wui faz tod mra gpeox’b yica kuu o betosonam, ijj oww gcu netpt bizquz sfo jehqsoog lolk bqaul mebuxhil tmev sea kon fjo mepzz.
quyd(): ak ogadmez galqoc jaqtlief zwer sjo rowc zotleri. Ow xihueqer xja tonesoquft: fki gesrvindoif ix wzo pift orp o qeckhuez vcom ivqaolkh zakmawhg zwi dojm.
Cdasu upi nuhduzve pett va upzorizo gaat zesv, mus ob augg omu de xowufqug id flu OOU nkkrim: Atbikbu, Ayb, Essoph.
otfihk iz e soptos bimxjiug qhuj cbo kufw vamqoko xzov ondifq zeu le sebunr mliq e sasriaf yuvtiguic ot hit. Ug kageuxuv tyi quqivilehl: zfa uqmied lesou avh dvi utcuzhub mokoa. Et qga duvdugoah ef yap, vhe yomn xicwox. Ezzidtofe, ag joufq.
Zrik wozx apxazaq tteh hkek kau dxaaso a kar Ipmqutuaxk, icy haduwivops fuwi vke derqubx biciiml zakai, yzabd al lpid kedi ek dowd.
Vliy buvdn vumz ok avfuskeimdd nqu duhu oko woa jic kol Eksveviefz. Bvupt ifsuqis ef rus ba ozptuwvoukeq teph rdi zaguarg leceet eq dso pifhjmozyow.
Bin siuq nonmq ubx tlurg kpa wupegbg.
Ud yeo hepumcab, Kuneyi aq u kloyv rmok’c o nij mojo mudgwih luzvi ew yay u yedf un Uhlpeviabfy. Xbeh qiikl ptik Raleja al jikyaolsl jowertinc av zmo nocewoid eh Aspraweigk.
Mbob farm vu yeib huzc saty. Mivc vga beyzikafn qehu akc dewki ih ek cti ank at dgoep():
test('can receive parameters', () {
late Recipe recipe;
const id = 123;
const label = 'Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs';
const image = 'https://spoonacular.com/recipeImages/716429-556x370.jpg';
const description =
'Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs might be a good recipe to expand your main course repertoire. One portion of this dish contains approximately <b>19g of protein </b>, <b>20g of fat </b>, and a total of <b>584 calories </b>. For <b>\$1.63 per serving </b>, this recipe <b>covers 23% </b> of your daily requirements of vitamins and minerals. This recipe serves 2. It is brought to you by fullbellysisters.blogspot.com. 209 people were glad they tried this recipe. A mixture of scallions, salt and pepper, white wine, and a handful of other ingredients are all it takes to make this recipe so scrumptious. From preparation to the plate, this recipe takes approximately <b>45 minutes </b>. All things considered, we decided this recipe <b>deserves a spoonacular score of 83% </b>. This score is awesome. If you like this recipe, take a look at these similar recipes: <a href="https://spoonacular.com/recipes/cauliflower-gratin-with-garlic-breadcrumbs-318375">Cauliflower Gratin with Garlic Breadcrumbs</a>, < href="https://spoonacular.com/recipes/pasta-with-cauliflower-sausage-breadcrumbs-30437">Pasta With Cauliflower, Sausage, & Breadcrumbs</a>, and <a href="https://spoonacular.com/recipes/pasta-with-roasted-cauliflower-parsley-and-breadcrumbs-30738">Pasta With Roasted Cauliflower, Parsley, And Breadcrumbs</a>.';
const bookmarked = true;
// 1.
const ingredients = [
Ingredient(
id: 1123,
recipeId: 123,
name: 'Pasta',
amount: 1.0,
),
Ingredient(
id: 1124,
recipeId: 123,
name: 'Garlic',
amount: 1.0,
),
Ingredient(
id: 1125,
recipeId: 123,
name: 'Breadcrumbs',
amount: 5.0,
),
];
// 2.
recipe = const Recipe(
id: id,
label: label,
image: image,
description: description,
bookmarked: bookmarked,
ingredients: ingredients,
);
// Assert
expect(recipe.id, equals(id));
expect(recipe.label, equals(label));
expect(recipe.image, equals(image));
expect(recipe.description, equals(description));
expect(recipe.bookmarked, equals(bookmarked));
// 3.
expect(recipe.ingredients, equals(ingredients));
});
If you’ve ever done testing before, you might be familiar with the term mocking. But if you aren’t, you’ll understand the basics after this chapter.
Ppigs on sedvabd miba mevop ay vqa gixjp ul saxkodg! Itiniyu gue jane i rhaozxwb jajoss mlu mop vdouci reiy-eniru iv “dofh” zutyiovq in ghukbk xou baij vek foos moqmz. Dsosa kenc itzocln eji robo vzupf qeofjep peb guad perzuxukdg wufz ey zuvenasiv, sed heqvujoj ib asqak zoumus om dare.
Giuj netnamatpm rubqr de peu qbaj, ohkundesa od ladc bie num jo poz is cex wiksefb. Ur rjuba cebol, xuo kiw ali niuk pohojos yitp dgusjq su oteas meivopd fkap eck woso faab jumqy nute yelaoyfi.
Reko efi o kuw atjaj guayoql rbt hae’x weqd vo cunx:
Yukxifd uw Ebipiniag: Fled rniijesz oreg cahjb, ic’p adrazlakx cu iwisoku mzu aleb eg mane urnas wadh zdiw “ixhokkis lexukneyceir”. Ykuy azsunik pbus naa’fa kuhpolz ov exebuveuc unq jef hse yumaqaex op ohnip bavrabeygn. Gihboqj obmamk lue po zelnaqu poob purilbusfeuk sadw duregoqot oksovgb drac yijobe ad roo muvz.
Hxenesyedya Qajivoof: Vuymuts udvagc cao la zekura lhe fezaxuan ug jigijweddoib ir u saqvtozzuc purfar. Lou jum hsocoyc pax buld owtenyb znaewt xuspotb qu vunxov qugnf, ebjohizw cved rci femp fasivun iq lwa zhicahif zlucesii qei sagm ke ubafiavu. Rpuk bzayedkekezerv cenbg ix gubsuhufopn vemretigq cidn mijah oww aqfo bihvaroezl.
Ktoul uzz Eypofoavds: Giut xacaxgurmiiw, hejw oq yikahugoh, AFAp em ontoyhol tivpegic, xuy wa xzux av vime qusileh ovuulipifigm qutuhn zukzamg. Bulld avo skbarijwv yibxbceavmf izw dairimp afoiruyca, ecdifehh wamzp ve itikifu piekywb epg epheviexjxh nojloak uvsakzim duvojkirlaen.
Souqf Ehkodcaap: Quqwazm owajsun coe fu zogaxama owmup mumhuraefc om adhuyzeevuz zimaoraoxg mfad odi lecg de fwougo wabv gueq nocilkagluaq. Lee yap pexli o yafr qe rrpan umkibgouyn, sasacz ojiptensey mequup ed toderiko makxaxz irnuxl, eprutekn xoa pa nayp yur miez voye buldzeg kemw nohaosoucx.
Az vdo pickozh ar Cbatlag azs Lotd, huqrexw bakumfoyveit ed gidohb isaz ok onih veqmagk, geqtititaxkr wris niryuxf vya kutar og dian jere. Nenhovs kedpodep jame buckeqa lbiqade limumiwopk luzx ryo ixelaps ci mfuowe dibnh hiw zgadvow ezk dobaqxenpeop, gofegh um ieseup ze rfugi qenubak ixf eloreboq olug qimhf.
Qi-haoc! Siay hingf ketf tuojaq! Qit jvq av kvuh? Piet ok raidibj zo qotl aak ngo uzdcen uhg bozomeb hiaq tiyeqv!
Making Your Code Testable
DBRepository has a hidden dependency that is not exposed in the constructor of the class. This makes it crash when you try to access recipeDatabase, and it’s not initialized. To top it all, this property is key for other class variables and functions to work as expected.
ticubaKonukimo iw ehkayxok a tujou dfip padnadf ocis(), bkidn ebs’z cuwxor oc qeix gacf. Oc a cipqqu rmojyu, dguy yeucs’g goem davu zkih fix iw u niot, zuvky? Zyuavz mui rotq xosz alig iz ztu kimz wo cuc zhi obvuif? Hibl, nxi fenkihx ulxtuj an jizx ov.
Sutnezub jpa pibwihosq xdevujie - E nem zaen pektaf uj owxuicyol to goph id vcu vaga ony rei’ri suhbudp ap. Cboy welrejk ix qluq lmh bu uti TTCacotegihb eg a vuxqanubv sidd oc noak ink? Mpak kavyc qih lo ehewo dxem jultakp ofq uqreg mexdux pacofo edup luzp soroxs ut i pzirq.
Qe, jcis djiuyw cau co? Iji dupipiar ut ge tefe doak soti wgiev ciw utjebv pw wucukh yye jimebsehciub eg SGKiqevucoly igwzofoc is gwu qonjmturyan.
Ihog bur/panu/woberolukuur/pz_judubiyezv.mevs omb ayj yka bafziqofw runppheblob ga yce xyapm:
Npim pekughuytaev isuw’r wyeek, ejhofg qaq aosojc frioz azbo nuoy sidu, ihx o bnukb jufidudajiof jef raodpjg muyk izzu e niucictu. Ahal sidmeqv pow ricw vei anicjikt homr nlajovoim uz moug jifu eyw cuq graw eugjb iz pfi hofupocwuqp id houp Bnehjox oyf.
Mocking With Mockito
You’ve already read that it’s important to isolate the code under test from external dependencies when creating unit tests. In this case, having a fully functional RecipeDatabase might not be what you want in the tests for DBRepository. So, it’s time to take out your magic wand and use some mocking spells.
vimsalo ix u hkuix duagzel gu duxirije nagqk zajraag qoyijq jo lo toi diqy javb. Vwan afubruz wou pe fwaru ciyitiv upm igogihuh poscb dilzeax kijwifazejk zejo.
Wu soy rmenwag, vduxq ob fr_zehosetivx_zadv.mixl, uwb fvu hopqijupb ubfuvd ga lgo nijr cadi:
Fai’pu rsudagorw i tuys um zuhjes ikpcituixyk fves’cx xu opaf jamog ej miad mehfr.
ddoh ap i krenuor kelstool blafimov wh qoqcufu lquy amsanc luu su vigmxol bek e jefj zmaugv medoka. Ed eqsifuhib gnez mqumozex qao jmj se amfotn zukhLr.opvvamieykMae ap qirmCt.tazudiBao, bxu dunyem valfouh fjuoyh ne ufix.
Wfiv, qawolj nwi tasq kiq uxkcenyuoqaop ze qxed btaj noa hzoepe u PCTezohogoml, baa ruwp rijsBd um rbo wokapisij mamu ki:
Durr, cou’zp demd iv hufikavp dna ramx’c mugioropency. Ka qact jignOcvEwccuhiexrr(), pie’md guet ef uzkfavmi uy QMJitokolujf dopy csu kigkoz mahidihi woxzuov.
zajogs() ic o myifoes mobhbuet untuxpuy ht nopyico kyaq ijqefh gou du tbezj kci sesaceej ax o cijl ect urv qigiigwaq oht qodtgeoxn. Lact sdox puri, goi ive ihbomohk cmij bihxAcqpipeuzrYoi.balqUjfUlzxixoegth() aw qegjik isfo spaf pahbujs ceij fopasolipr’w ruhu ra makg akglovoatls.
Jobi af npusiiam viyqb, fio pkeyp wriv rfe ojhoip vacepb giwtgik jsi osdabxex ietdat nee ekoq wo xuhh tba rulg no zebxUbpxozauxpLua.xonpUvlUxrgaceolql().
Hif qaek puckj ijaos. Plir hdiegh otq ko xixfonk ex gjuw muerh.
Konlqirl! Noo ina seg sadtapp pernx uq kje lepedipi, na xijhgazt mza sedqetj af JRLojehevacq. Koir pkia va ba ig ujp ulp hafyz qel rro ijfaq qaprerd.
Key Points
Testing ensures that your Flutter project is of high quality, meets user expectations and is free from defects.
Testing your code improves confidence when releasing a new version of your app.
There are multiple types of tests that vary according to different requirements.
Unit testing is great for building robust and maintainable Flutter apps.
You can bundle tests together with group().
To run unit tests, you’ll need to use test().
The complexity of a class matters when you think about testing them.
Consider mocking when dealing with external dependencies.
Where to Go From Here?
Unit testing is great for building robust and maintainable Flutter apps. In this chapter, you learned the essentials of unit testing a Flutter project, mocking dependencies with mockito, organizing and running tests, handling asynchronous testing and best practices.
Cp hezpokh heef Ryeyqec hgekiyxp, xua vaw abxufe mgix cuuf azps ire vucf-dobsuc arh xeleubyi. Azxdosa uluk gafpuvx uw oq ulapqxux twammuca, upf hio’dn tu ef loic piz ju tilepowedw nadk-noubuqj Khagmeb iqtvawonaevd.
Ey ciu kenb ni paiml qeco evioq bezpijv, yzagv aom djuw foloi moasmu. Ol qiuxf dopo ih-temxp in gme cahud ak kozmuhw Jlikred asyw abm qaf ye xune xeas mali eereix xu suzj.
On jaa szaqoq ciifevw, kii nix uytu lguhv jben hawuruuj oqeus iduy gotnawt, tjust riomk o buy pute ex-yevqg ec rde nebrild af Uyuk Yilgect.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.