IOS Unit Testing By Example

3y ago
397 Views
84 Downloads
1.63 MB
14 Pages
Last View : 17d ago
Last Download : 2m ago
Upload by : Francisco Tran
Transcription

Extracted from:iOS Unit Testing by ExampleXCTest Tips and Techniques Using SwiftThis PDF file contains pages extracted from iOS Unit Testing by Example, publishedby the Pragmatic Bookshelf. For more information or to purchase a paperback orPDF copy, please visit http://www.pragprog.com.Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; thecontent is otherwise identical.Copyright 2020 The Pragmatic Programmers, LLC.All rights reserved.No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,without the prior consent of the publisher.The Pragmatic BookshelfRaleigh, North Carolina

iOS Unit Testing by ExampleXCTest Tips and Techniques Using SwiftJon ReidThe Pragmatic BookshelfRaleigh, North Carolina

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trademarks of The Pragmatic Programmers, LLC.Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.Our Pragmatic books, screencasts, and audio books can help you and your team createbetter software and have more fun. Visit us at https://pragprog.com.The team that produced this book includes:Publisher: Andy HuntVP of Operations: Janet FurlowExecutive Editor: Dave RankinDevelopment Editor: Michael SwaineCopy Editor: Adaobi Obi TultonIndexing: Potomac Indexing, LLCLayout: Gilson GraphicsFor sales, volume licensing, and support, please contact support@pragprog.com.For international rights, please contact rights@pragprog.com.Copyright 2020 The Pragmatic Programmers, LLC.All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording,or otherwise, without the prior consent of the publisher.ISBN-13: 978-1-68050-681-5Encoded using the finest acid-free high-entropy binary digits.Book version: P1.0—June 2020

For Kay, who believed in me

CHAPTER 1Assert YourselfEvery company wants to reduce their costs. In software, making changes isinexpensive: we wiggle our fingers on keyboards. So where do the costs lie?Aside from development time, they lie in errors, and how much time it takesto detect these errors. (They also lie in building the wrong thing, which isbeyond the scope of this book.)To detect problems, mobile developers use all kinds of feedback loops. Forexample, we keep an eye on crash reports and customer complaints. Butthat’s the longest loop. After making an incorrect change, it takes a long timeto get that feedback.To try to prevent errors from making it all the way to customers, companiesuse manual testing. The best quality experts apply talent and creativity to doexploratory testing. Let’s not waste their time asking them to follow steps inmind-numbing repetition. Besides, the time between making an error andgetting feedback from testers is still long.What if we could do a large amount of testing using computers? In fact, whatif the developer’s own computer could provide feedback? And what if thisfeedback were so quick, you could get it on every change you made? Thiskind of rapid feedback is a game changer. It not only catches problemsquickly, it can change the way you code.This is what unit tests are for. Maybe you haven’t done any unit testing inyour iOS apps yet. Or maybe you’ve been able to test some logic, but yourtests don’t cover the iOS-specific parts. (And those are important parts.)Wherever you are in your unit testing journey, the goal for this book is thesame: to reduce your costs. Click HERE to purchase this book now. discuss

8What Are Unit Tests Anyway?There’s some confusion about what makes a test a unit test. Many people tryto focus on the “unit” part of the name, thinking it describes testing a unitof production code. I’ll continue to use the term because it’s widespread, butlet’s forget about asking “What’s a unit?” Instead, here’s my definition:Unit tests are a subset of automated tests where the feedback is quick, consistent, and unambiguous.Quick: A single unit test should complete in milliseconds. We want thousandsof such tests.Consistent: Given the same code, a unit test should report the same results.The order of test execution shouldn’t matter. Global state shouldn’t matter.Unambiguous: A failing unit test should clearly report the problem it detected.In our first chapter, we’ll explore the fundamental tool of unit testing: assertions. You’ll learn the most common assertions in the Swift XCTest frameworkin a hands-on way.If you’re a seasoned unit test writer, you may want to skip ahead to the KeyTakeaways, on page ?. But even if you’ve written some tests, it can be goodto go over the fundamentals. What are assertions for? What do they report?Do you know how to choose the right assertion for the right job? This chapterwill help you get familiar with these tools, which we’re going to be using allthe time.Create a Place to Play with TestsAssertions give unit tests a way to state their expectations. The tests fail if theseexpectations aren’t met. Let’s make a place outside of your actual projects wherewe can experiment with how they work. Throughout this book, you’ll learn newconcepts by playing in these safe spaces. Then in the exercises at the end ofeach chapter, you’ll begin applying these concepts to your own code.When it comes to learning, reading doesn’t come close to doing. If you takethe code from the examples and type them into your computer, your learningwill go deeper. So I encourage you to open your IDE of choice and give it ago. (The examples will use Xcode.)Let’s start by making a place where we can play with tests. Xcode playgroundsare tricky to use with XCTest, so we won’t do that. Instead, we’ll make a newproject. In the Xcode menu, select File New Project or press Shift - D - N . Click HERE to purchase this book now. discuss

Create a Place to Play with Tests 9It doesn’t matter what type of project we make as long as it comes with unittest support. But since we’re going to focus on testing iOS apps, we may aswell get used to what that feels like. First, create an iOS Single View App.Next, choose any options you like for your new project. In the examples thatfollow, we’ll use the project name AssertYourself. But make sure to do the following: Choose “Swift” as the language. Choose “Storyboard” as the user interface. (Don’t select “SwiftUI.”) Select the check box for “Include Unit Tests.”You now have a project set up to run unit tests on an iOS app, which we’lluse for our learning experiments.Select the initial test file that the new project created. Its name will be theproject name followed by Tests. So for this project, find AssertYourselfTests.swift.Delete every method in the AssertYourSelfTests class, leaving only an empty shell:class AssertYourselfTests: XCTestCase {}Make sure your destination is set to an iOS simulator. Any simulator will do.Now in the Xcode menu, select Product Test or press D - U . You might wantto learn this keyboard shortcut—you’ll be doing this often. Think U for “unittest” to remember it.This will perform several steps and then run the tests. You won’t see any testfailures because there are no tests. You may see this image show briefly onyour screen:If you didn’t see that image, go to Xcode Preferences and select the Behaviorstab. There you can customize what happens when testing succeeds. To displaythe image, select the check box “Notify using bezel or system notification,” asshown in the image on page 10.Now we’re ready to play. In the following sections, we’ll experiment withassertions to learn more about them. Click HERE to purchase this book now. discuss

10Write Your First AssertionNow that we have a home for tests, let’s go over how to use the testingmechanism. How does a test communicate success or failure? What doesXcode show you when a test fails? What does it show when a test succeeds?The way a test reports a failure to XCTest is through assertions. Let’s startwith the simplest assertion. Add the following method to the selfTests/AssertYourselfTests.swiftfunc test fail() {XCTFail()}First, what makes this function a test? It lives within a subclass of XCTestCase.It isn’t declared private.Its name starts with test.It takes no parameters.It has no return value. Click HERE to purchase this book now. discuss

Write Your First Assertion 11Why the underscore in the test name? This goes against Swift’s normal “camelcase” naming conventions. But good test names often contain three parts. I liketo use underscores to separate these parts and camel case within each part. I’llexplain this further when we have a test name describing its inputs andexpected output. For now, know that the underscores separate the test nameinto parts, which we’ll look at in Add Tests for Existing Code, on page ?.This test does nothing but fail. Run it by pressing D - U and observe whathappens. First, you may see this image show briefly on your screen:(If you didn’t see that image, go back to the Behaviors tab in Xcode preferences.Only this time, customize what happens when testing fails.)Looking at the earlier source file within Xcode, you’ll see the TestStatus Icon in the left-hand gutter, like the image to the right.X marks the spot in two places: the method and the class containing themethod. The method is a test, also known as a test case. The class representsa test suite, which is a collection of tests. The X icon shows a failure at boththe test level and the suite level. You’ll also see that Xcode highlighted theXCTFail() line and added an annotation to its right.So Xcode has marked the following: The class containing a failing test The method defining a failing test The line with the failed assertionNow add // before XCTFail() to comment out the assertion. Press D - U to run thetests. You’ll see the following: The annotation disappears from the assertion line The test status icons change from red Xs to green check marks,like the image to the right. Click HERE to purchase this book now. discuss

12This may look trivial, but it’s significant. It means we have a way to fail a test,with Xcode showing us where the test reported the failure. You can also seethat when a test finishes without triggering any assertions, the test passes.As you progress in your testing ability, you’ll even be able to writeassertions defining what you want the code to do. Then you canchange the production code until it passes the tests. We’ll returnto this topic in Chapter 20, Test-Driven Development Beckons toYou, on page ? at the very end of the book.Add a Descriptive MessageSeeing the location of a test failure is a good start. But when a test fails, wehave to diagnose what went wrong. We can save time for ourselves in thefuture by having the assertion explain anything we know at the point of failure.XCTFail() can take a String parameter as an assertion message. Let’s see how itworks. Add the following method to the rselfTests.swiftfunc test fail withSimpleMessage() {XCTFail("We have a problem")}Run the tests. Note how Xcode puts the message in the annotation:Since the annotation is on the same line as the failure, you may ask, “Couldn’twe have put a message to ourselves in a code comment?” But this isn’t theonly place the message appears.In the Xcode menu, select View Navigators Show Issue Navigator (or pressD - 5 ). The Navigator column on the left will show any issues, including testfailures. You may need to click the Buildtime selector, shown here:As you can see, the descriptive failure message appears in the Issue Navigator.It also appears in the test logs, which other tools may process—especially oncontinuous integration servers. Click HERE to purchase this book now. discuss

Add a Descriptive Message 13Thanks to Swift’s string interpolation, XCTFail() can do more than spit out astring literal. Add this to the rselfTests.swiftfunc test fail withInterpolatedMessage() {let theAnswer 42XCTFail("The Answer to the Great Question is \(theAnswer)")}(Strings are italicized in code samples. That’s a backslash \ for string interpolation, not a pipe .)Run the tests, and you’ll see the following:failed - The Answer to the Great Question is 42 Click HERE to purchase this book now. discuss

iOS Unit Testing by Example XCTest Tips and Techniques Using Swift Jon Reid The Pragmatic Bookshelf Raleigh, North Carolina . Aside from development time, they lie in errors, and how much time it takes . kind of rapid feedback is a game changer. It not only catches problems quickly, it can change the way you code. .

Related Documents:

iOS SDK Overview The iOS SDK contains the code, information, and tools you need to develop, test, run, debug, and tune applications for iOS. Xcode provides the launching point for testing your applications on an iOS device, and in iOS Simulator. iOS Simulator is a platform that mimics the basic iOS

iOS 14 and the Essential Eight 5 iOS 14 platform feature summary and risk considerations 7 . Email applications 11. iii Microsoft Office for iOS 12 iOS Calendar 12 iOS Contacts 12 iOS Camera 13 . iPhone and iPad running iOS 14. Throughout this guide, devices and combinations of softwar

Router Software Origin Validation (RPKI RTR & BGP Modifications) available in Cisco IOS and IOS-XR Cisco IOS code available in IOS XE-3.5.0/15.1(3)S Cisco IOS platforms targeted ASR1K, 7600, ME3600/ ME3800, ASR 903 Cisco IOS-XR available in the XR-4.2.1 Cisco IOS-X

XML Conversion Draft - 03/07/2011 iii Cisco IOS Server Load Balancing Configuration Guide OL-24559-01 CONTENTS CHAPTER 1 Cisco IOS SLB Features Roadmap 1-1 CHAPTER 2 Information About Cisco IOS SLB 2-1 Overview 2-1 Benefits of IOS SLB 2-3 Cisco IOS SLB Features 2-4 Routing Features 2-4 Algorithms for Server Load Balancing 2-5 Bind ID Support 2-6

2.1 iOS Developer Programs iOS developers use development tools like Xcode and iOS simulators to develop apps. To distribute their apps to le- gal (or non-jailbroken) iOS devices, app developers must join the iOS developer programs[6]. There are three type- s of iOS developer programs:standard program,enterprise programanduniversity program.

dalam GNS3, sehingga bisa terkoneksi antar perangkat IOS XRv dan perangkat IOS. 1. Sebelum integrasi IOS XRv terlebih dahulu memasukkan perangkat IOS ke dalam GNS3, dalam hal ini yang digunakan adalah IOS C2691 (c2691-advipservicesk9-mz.124-15.T6.bin) GNS3 - Edit - IOS Images and hypervisors. Kemudian masukan image filenya.

iPhone 11 iOS 13.0或以上 iPhone 11 Pro iOS 13.0或以上 iPhone 11 Pro Max iOS 13.0或以上 平板電腦 iPad 4或更新型號 iOS 10.0 或以上 iPad mini 4或更新型號 iOS 10.0 或以上 . Lenovo Tab3 7 Essential

ACE Elite iOS U9P2R9XL8S.com.netspend.mobileapp.ace 1 1 Acoustiblok iOS com.studiosixdigital.acoustiblok 1 1 ACPS iOS com.blackboard.community.acps 1 1 ACS Central Science iOS org.acs.pubs.centralscience 1 1 ACT 2016 iOS me.doubledutch.tqbhg.act2016 1 1 ACT‐IAC iOS me.doubledutch.actia