<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yağız Erbay on Medium]]></title>
        <description><![CDATA[Stories by Yağız Erbay on Medium]]></description>
        <link>https://medium.com/@yagiz.erbay92?source=rss-8bc53ed20b67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WHEyKLBWIOu38Ywmx9GFwQ.jpeg</url>
            <title>Stories by Yağız Erbay on Medium</title>
            <link>https://medium.com/@yagiz.erbay92?source=rss-8bc53ed20b67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:23:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yagiz.erbay92/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS App Security:]]></title>
            <link>https://medium.com/adessoturkey/ios-app-security-96c32ba4e036?source=rss-8bc53ed20b67------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c32ba4e036</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Yağız Erbay]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 08:20:50 GMT</pubDate>
            <atom:updated>2023-12-25T08:20:50.188Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A Detailed Guide on iOS App Security</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRtQVUldb7O939de8L1f1Q.jpeg" /></figure><p>Nowadays, security stands as a top-priority subject within the IT industry. Both individual users and corporations are displaying an increasing awareness of the concepts of data security and privacy. This emphasis extends to mobile applications, largely due to their proximity to end-users. The frequent usage and user-friendly nature of mobile applications often result in the storage of significant volumes of sensitive personal data.</p><p>While iOS is recognized as a highly secure mobile operating system, this doesn’t imply that you should forego additional security measures when creating an iOS application.</p><p>In this article, our primary focus will be learning the fundamental aspects of iOS security.</p><p><strong>1) App Switcher Snapshot Controls</strong></p><p>Sensitive information can potentially be revealed in the snapshot images that iOS displays during app switching. Additionally, iOS captures a screenshot each time an app is moved to the background, and this image is stored in the app’s sandbox, making it susceptible to unauthorized access by potential attackers.</p><p><strong>Blocking the screen view</strong></p><p>If your application showcases sensitive information, it’s essential to conceal the content when the app enters the background.</p><p>This can be achieved by making direct adjustments to the SceneDelegate file:</p><ul><li>Create an imageView.</li><li>Insert it when your app enters the foreground.</li><li>Remove it when your app becomes active again.</li></ul><pre>// App Delegate<br>private lazy var coverView: UIImageView = {<br> let imageView = UIImageView(frame: self.window!.frame)<br> imageView.backgroundColor = UIColor.black<br> return imageView<br>}()<br>// …<br>func applicationWillResignActive(_ application: UIApplication) {<br> self.window?.addSubview(coverView)<br>}<br>// …<br>func applicationWillEnterForeground(_ application: UIApplication) {<br> coverView.removeFromSuperview()<br>}</pre><p><strong>2) Printing Logs</strong></p><p>Developers frequently call the print() function for debugging purposes. However, a potential issue may arise when these calls are left in the code, as they may contain sensitive information that could be exploited by an attacker to compromise your security.</p><pre>#if DEBUG<br>print(&quot;log&quot;)<br>#endif</pre><p>It is a good practice to use compiler flags; by doing this, print() functions only work in debug mode.</p><p><strong>3) Jailbreak Prevention Methods</strong></p><p>iOS is engineered to provide reliability and security right from the moment your device is powered on. It incorporates built-in security mechanisms to safeguard against malware, viruses, and ensures the protection of personal and corporate data.</p><p>However, unauthorized alterations to iOS, commonly referred to as “jailbreaking,” bypass these security features and can lead to various problems, including security vulnerabilities, instability, and reduced battery life for the compromised iPhone.</p><p><strong>There are several ways to detect and prevent jailbreaks in iOS apps:</strong></p><p><strong>Verifying the presence of particular files or directories:</strong> An approach to identifying jailbreak activity is by inspecting the existence of specific files or directories that are typically associated with jailbreaking tools.</p><pre>if FileManager.default.fileExists(atPath: &quot;/Applications/Cydia.app&quot;) {<br> // Device is jailbroken<br>} else {<br> // Device is not jailbroken<br>}</pre><p>The directory at /Applications/Cydia.app is frequently found on jailbroken devices, as it serves as the installation location for the Cydia app. Cydia is a well-known package manager used on jailbroken devices, enabling users to explore and install third-party apps and customizations not accessible through the official App Store.</p><p><strong>Leveraging Apple’s Provided APIs:</strong> Apple offers a range of APIs that are helpful in identifying jailbreaking activities. For instance, the canOpenURL() function within the UIApplication class is a valuable tool for verifying whether the device can access a URL known to be associated with jailbreak tools.</p><p>In the following Swift code snippet, we determine if the device can open the Cydia URL, a common indicator of jailbreaking tools:</p><pre>if UIApplication.shared.canOpenURL(URL(string: &quot;cydia://package/com.example.package&quot;)!) {<br> // Device is jailbroken<br>} else {<br> // Device is not jailbroken<br>}</pre><p>The functionality of the canOpenURL() function serves as an effective technique for identifying jailbreak activity. Jailbreak tools often make alterations to the operating system, enabling the installation and operation of unauthorized applications and customizations.</p><p>Consequently, jailbroken devices possess the capability to launch URLs that are typically restricted on non-jailbroken devices. Through the evaluation of the device’s ability to open the cydia://package/com.example.package URL, developers can deduce the presence of a jailbroken device with potential system-level modifications.</p><p><strong>Implementing Custom Verification Procedures</strong>: Developers also have the option to create their own checks to identify jailbreak activities. One approach is to examine specific system libraries or frameworks that are typically absent on non-jailbroken devices. The following Swift code example illustrates how to verify the existence of the libsubstrate.dylib library, a component commonly utilized by jailbreak tools:</p><pre>let libraryPath = &quot;/Library/MobileSubstrate/MobileSubstrate.dylib&quot;<br>if FileManager.default.fileExists(atPath: libraryPath) {<br> // Device is jailbroken<br>} else {<br> // Device is not jailbroken<br>}</pre><p>Beyond all that, several files and directories can be examined by developers to identify jailbreak indications in on iOS devices. Here are a few instances:</p><pre>static var suspiciousSystemPathsToCheck: [String] {<br> return [&quot;/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist&quot;,<br> &quot;/Library/MobileSubstrate/DynamicLibraries/Veency.plist&quot;,<br> &quot;/private/var/lib/apt&quot;,<br> &quot;/private/var/lib/apt/&quot;,<br> &quot;/private/var/lib/cydia&quot;,<br> &quot;/private/var/mobile/Library/SBSettings/Themes&quot;,<br> &quot;/private/var/stash&quot;,<br> &quot;/private/var/tmp/cydia.log&quot;,<br> &quot;/System/Library/LaunchDaemons/com.ikey.bbot.plist&quot;,<br> &quot;/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist&quot;,<br> &quot;/usr/bin/sshd&quot;,<br> &quot;/usr/libexec/sftp-server&quot;,<br> &quot;/usr/sbin/sshd&quot;,<br> &quot;/etc/apt&quot;,<br> &quot;/bin/bash&quot;,<br> &quot;/Library/MobileSubstrate/MobileSubstrate.dylib&quot;]<br> }<br><br> static func isSuspiciousSystemPathsExists() -&gt; Bool {<br> for path in suspiciousSystemPathsToCheck {<br> if FileManager.default.fileExists(atPath: path) { return true }<br> }<br> return false<br> }</pre><p><strong>4) UserDefaults and Keychain</strong></p><p>UserDefaults are saved as a property list file within the Preferences directory of your app, making them accessible in a similar way to app snapshots. The lack of security or encryption is intentional because UserDefaults aren’t intended for the storage of sensitive information. Instead, they serve as an interface for adjusting an app’s behavior in alignment with user preferences. For instance, they are commonly used for settings like preferred units of measurement or feature toggle values.</p><p><strong>There is also the option of using property lists.<br></strong>A property list file, commonly referred to as a plist file, is a specialized file format used for storing data in key-value pairs. In fact, plist files are essentially XML files with a distinct naming style within the Apple ecosystem. To draw a parallel, plist files share similarities with Swift dictionaries, which are also a collection type capable of holding key-value pairs of data. It contains a large number of default settings, configurations, and information regarding the app, but more entries can be added on demand.</p><p>But storing data in plist files in Swift can pose various security risks, including:</p><ol><li>Data Exposure: Plist files are stored in plain text and can be easily accessed. Sensitive information, such as passwords or API keys, can be exposed if not properly encrypted.</li><li>Lack of Encryption: Plist files lack built-in encryption. Without encryption, the data stored in these files is vulnerable to unauthorized access.</li><li>Tampering: Plist files can be modified by anyone with access to the file system. This can lead to data tampering and potentially compromise the integrity of your app’s data.</li><li>No Access Control: Plist files do not offer access control mechanisms. Any process or app running on the device may access these files.</li><li>Data Leaks: Improper handling of plist files can result in data leaks, where sensitive information is inadvertently exposed to other apps or to external sources.</li></ol><p>On the other hand, we have the Keychain, specifically designed for keeping user secrets secured. The Keychain services API offers a secure method for storing small portions of users’ sensitive data within an encrypted database known as a Keychain.</p><p>In order to save and retrieve the user data, you can just use the following code.</p><pre>func save(key: String, data: NSData) -&gt; OSStatus {<br> let query = [<br> kSecClass as String : kSecClassGenericPassword as String,<br> kSecAttrAccount as String : key,<br> kSecValueData as String : data ] as [String : Any]<br> <br> SecItemDelete(query as CFDictionary)<br> return SecItemAdd(query as CFDictionary, nil)<br> }<br> <br> func load(key: String) -&gt; NSData? {<br> let query = [<br> kSecClass as String : kSecClassGenericPassword,<br> kSecAttrAccount as String : key,<br> kSecReturnData as String : kCFBooleanTrue ?? false,<br> kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any]<br> <br> var dataTypeRef:AnyObject? = nil<br> let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &amp;dataTypeRef)<br> <br> if let data = dataTypeRef {<br> if status == noErr {<br> return (data as? NSData)<br> }<br> }<br> return nil<br> }</pre><p>Within the Keychain, you have the ability to securely store items like passwords and other sensitive information that users explicitly value.</p><p><strong>5) Data Protection</strong></p><p>Nevertheless, the Keychain isn’t a suitable choice when dealing with more extensive sensitive data beyond passwords or tokens. In such cases, Data Protection comes into play. Data Protection is an iOS feature designed to safeguard an app’s files and prevent unauthorized access to them. It’s automatically activated on devices secured with a password. This means that files remain unencrypted when the device is unlocked. However, even if someone attempts to access the data directly from the device’s storage, it remains inaccessible.</p><p>Data Protection secures the data stored in the flash memory. The encryption and decryption procedures are seamless, accelerated by hardware, and remain inconspicuous to the user.</p><p>Enabling data protection is not a prerequisite, since beginning with iOS 7, all application files are automatically encrypted by default. The default protection level is “<em>complete until first user authentication”</em>.</p><p>Usually , there are four levels of protection available:</p><ul><li><strong>No protection</strong>. The file is always accessible.</li><li><strong>Complete until first user authentication</strong>. The file remains inaccessible until the user unlocks the device for the first time. Following the initial device unlock, the file stays accessible until the device is powered down or undergoes a reboot.</li><li><strong>Complete unless open</strong>. You can exclusively access existing files when the device is in an unlocked state. Once a file is open, you may continue to access that file, even if the user locks the device.</li><li><strong>Complete.</strong> The file is accessible only when the device is unlocked.</li></ul><p>The protection level is selected for all the files within the app’s file system, but you have the option to programmatically override the specific file protection level.</p><p>You can encrypt a new file like in the following script:</p><pre>do {<br> try data.write(to: fileURL, options: .completeFileProtection) // Specify protection level<br>}<br>catch {<br> // Handle error.<br>}</pre><p>You can also encrypt an existing file:</p><pre>do {<br> try (fileURL as NSURL).setResourceValue( <br> URLFileProtection.complete,<br> forKey: .fileProtectionKey) // Set URLFileProtection<br>}<br>catch {<br> // Handle error.<br>}</pre><p><strong>6) SSL (Secure Socket Layer)</strong></p><p>SSL, which stands for Secure Socket Layer, is a protocol produced to facilitate secure communication exclusively between two devices or networks via the internet.</p><p>This protocol is used to encrypt data that is transmitted between a web server and a web browser, making sure that the confidentiality and security of the data.</p><p>For applications and websites dealing with sensitive information such as credit card details, login credentials, and personal data, SSL is crucial. SSL allows these applications and websites to effectively safeguard their users’ data, preventing interception by malicious entities.</p><p><strong>What Is SSL Pinning?</strong></p><p>SSL pinning is a security method that matches a specific SSL certificate with a particular web server. Its primary objective is to prevent man-in-the-middle (MITM) attacks.</p><p>SSL pinning achieves this by allowing only trusted SSL certificates to establish secure connections between a client application (e.g., an iOS app) and the server.</p><p>In an iOS app, SSL pinning guarantees that the client exclusively accepts the SSL certificate that has been pinned or its associated public key during the initiation of a secure connection with the server.</p><p>In the event that the server provides a different SSL certificate for any reason, the connection will be immediately terminated. Meaning, the client will be unable to advance with the request, even if the certificate is authorized by a trusted certificate authority (CA).</p><p>SSL pinning steps can be listed as shown below:</p><p>1. The client device initiates a connection request to the server, server listens for the incoming request.</p><p>2. Server returns with the response, including the public key and certificate.</p><p>3. Client verifies the certificate and sends an encrypted key to the server.</p><p>4. Server decrypts the key and sends encrypted data back to the client machine.</p><p>5. Client receives and decrypts the encrypted data.</p><p><strong>Types of SSL Pinning</strong></p><ul><li><strong>Pin the certificate</strong>: You download the server’s certificate and embed this in your app bundle. During runtime, the app compares the server’s certificate to the one you’ve embedded.</li><li><strong>Pin the public key</strong>: You retrieve the certificate’s public key and embed it in your code as a string. During runtime, the app compares the certificate’s public key to the one embedded hash string in your code.</li></ul><p><strong>7) Code Obfuscation</strong></p><p>Code obfuscation in iOS involves transforming the source code of an application to make it more challenging for reverse engineers to understand or decompile. This process aims to enhance the security of an iOS app by making it harder for attackers to analyze the code and discover vulnerabilities.</p><p><strong>iXGuard</strong></p><p>iXGuard is designed to enhance the security of your Swift and Objective-C applications and SDKs by decreasing the risks of reverse engineering and hacking. It enhances the robustness of their code, allowing for vigilant monitoring of both their integrity and the security.</p><p>Some of iXGuard’s features are listed below:</p><ul><li>Configuring iXGuard is a simple process. With a single configuration file, it can be easily set up to protect entire applications or specific functions.</li><li>iXGuard offers built-in support for both native iOS (Objective-C, Swift) and cross-platform applications (Cordova, Ionic, React Native, Unity).</li><li>iXGuard provides functionality to help you efficiently and effectively protect your application or SDK: Its In-App Assistant autonomously produces configuration for your application and its Protection Report helps you improve your protection before release.</li><li>iXGuard integrates seamlessly with Guardsquare’s real-time threat monitoring platform, ThreatCast. ThreatCast provides visibility into the real threats possible to compromise your app and enables you to prepare your security configs for the constantly evolving threat possibilities.</li></ul><p><strong>Code hardening</strong></p><p>iXGuard denies attackers from gaining access into your source code and modifying it, or extracting valuable information from it.</p><ol><li>Obfuscation of names of classes, fields, and methods, of arithmetic instructions, control flows and method calls.</li><li>Encryption of sensitive strings, assets, and resources.</li></ol><p><strong>Runtime application self-protection (RASP)</strong></p><p>iXGuard enables applications and SDKs to monitor the integrity of their code and that of the environment in which they are running.</p><ol><li>Environment integrity checks, including jailbreak detection and debugger detection.</li><li>Application integrity checks, including repacking detection.</li><li>Code integrity checks, including hook detection, method swizzling prevention, and code tracing detection.</li></ol><p><strong>Conclusion</strong></p><p>Leaving your app’s security to chance is never a good idea. An unsecured application can be lucrative for potential attackers to gain access to the app’s files and compromise sensitive information. Using secure coding practices is essential in protecting users’ data from theft or tampering.</p><p>As developers, our aim is to minimize the risk of data or information compromise within our app. This can be achieved by following the established best practices for app security.</p><p><strong>If you have any questions, please feel free to ask in the comments.</strong></p><p><strong>Thanks for reading! 🚀</strong></p><p>References:</p><ul><li><a href="https://www.shashankthakur.dev/2020/09/how-to-make-ios-app-secure.html">How to make an iOS App Secure?</a></li><li><a href="https://infinum.com/blog/how-to-make-your-ios-apps-more-secure-with-ssl-pinning/">How to Make Your iOS Apps More Secure with SSL Pinning</a></li></ul><p><a href="https://www.guardsquare.com/ixguard">https://www.guardsquare.com/ixguard</a></p><p>Source Code:</p><p><a href="https://github.com/yagizerbay92/iosAppSecurity">https://github.com/yagizerbay92/iosAppSecurity</a></p><p><strong>A Detailed Gguide on iOS App Security</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c32ba4e036" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/ios-app-security-96c32ba4e036">iOS App Security:</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in Swift]]></title>
            <link>https://medium.com/adessoturkey/unit-testing-in-swift-c1607da61e13?source=rss-8bc53ed20b67------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1607da61e13</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Yağız Erbay]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 10:42:12 GMT</pubDate>
            <atom:updated>2023-01-16T10:42:12.024Z</atom:updated>
            <content:encoded><![CDATA[<p>How to Get Started with iOS Unit Testing: Fundamentals</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BFrd1R4kRlsVe8dI-70veA.jpeg" /></figure><h3><strong>What is unit testing?</strong></h3><p>In computer programming, a “unit test” is a software testing method that initializes a small chunk of our project and verifies its behavior independently from other parts. Most common unit tests contain three phases:</p><p>First, it initializes a small piece of code it wants to test (also known as the “system under test”, or SUT) after that, it activates the system under test (usually by calling a method); and finally, it observes the resulting behavior. If the observed behavior is consistent with the expectations, the unit test passes; otherwise, it fails, indicating that there is a problem somewhere in the system under test.</p><p>These three unit test phases are also known as Arrange, Act, and Assert, or simply AAA.</p><h3><strong>Advantages of unit tests</strong></h3><ul><li>Unit tests reduce or eliminate potential bugs in new and existing features.</li><li>Tests reduce development costs when a code change is required.</li><li>You can improve the design without breaking it.</li><li>You can refactor your code easily (at least you realize where your refactored code fails before it becomes a bigger concern).</li><li>Unit tests force you to plan before you code.</li><li>And most importantly, unit tests act as a fail-safe mechanism against most of our programmers’ worst nightmare: making a change in a piece of code and not knowing what is going to break, crash, or duplicate etc., you name it.</li></ul><h3><strong>Disadvantages of unit tests</strong></h3><ul><li>They increase the amount of code that needs to be written.</li><li>Unit tests cannot and will not catch all bugs in an application. There is no way it can test every logic path or find integration and system defects.</li><li>It will increase the development time so that your development needs may not fall in line with the project owners’ tight schedules (deadlines).</li></ul><h3><strong>How to add a unit test target to the project?</strong></h3><p>If you are starting your project from scratch, you should add a unit test target to your Xcode project.</p><p>There are two different approaches to doing that:</p><ul><li>First one is during project creation, by selecting <strong>Include Unit Tests</strong> checkbox then clicking Next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jVx9vV-H-tr44IbBB1ZZg.png" /></figure><p>If you already have a project, then;</p><ul><li>First go to File &gt; New &gt; Target.</li><li>Select Unit Testing Bundle.</li><li>Then click Next</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDT5F5UCy3B-aba03wWIng.png" /></figure><h3><strong>Apple’s XCTestCase</strong></h3><p>Okay, people, if you are at this stage, then your project is ready to roll and Xcode has already created a unit test class for you. This class inherits the <a href="https://developer.apple.com/documentation/xctest/xctestcase">XCTestCase</a> class, which will act as a base class for all unit tests that you will be adding in the future. A standard test case contains setup and teardown functions. These functions are called before and after each of the test functions, respectively. This cycle allows us to set up prerequisites before the tests are run and reset any variables, references, etc. after the completion of each unit test.</p><blockquote>To know more about the setUp() and tearDown() cycles, you can check Apple’s official documentation <a href="https://developer.apple.com/documentation/xctest/xctestcase/set_up_and_tear_down_state_in_your_tests">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmTxcdFot7qAc0Fgs-d1_g.png" /></figure><p>Starting a function in a XCTestCase class with “test” tells Xcode that the indicated function is a unit test. For each unit test function, you will see an empty diamond shape aligned with the test method declaration listed in the gutter. Clicking on the given diamond icon will run the specific unit test.</p><h3><strong>Let’s code!</strong></h3><p>Let’s start with a basic project to compare vehicle types:</p><pre>import Foundation<br><br>class Vehicle {<br>    private var miles = 0<br>    private var type: VehicleType<br>    <br>    init(type: VehicleType) {<br>        self.type = type<br>    }<br>    <br>    func startEngine(minutes: Int) {<br>        var speed = 0<br>        <br>        switch type {<br>        case .PassengerAircraft:<br>            speed = 575<br>        case .FighterJet:<br>            speed = 1320<br>        case .HighSpeedTrain:<br>            speed = 217<br>        case .Car:<br>            speed = 100<br>        case .Bicycle:<br>            speed = 10<br>        }<br><br>        self.miles = speed * (minutes / 60)<br>    }<br>    <br>    func returnMiles() -&gt; Int {<br>        return self.miles<br>    }<br>}<br><br>enum VehicleType {<br>    case PassengerAircraft<br>    case FighterJet<br>    case HighSpeedTrain<br>    case Car<br>    case Bicycle<br>}</pre><p>Now, we can initialize and use the vehicle object “mercedes” in a ViewController:</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        let mercedes = Vehicle(type: .Car)<br>        mercedes.startEngine(minutes: 60)<br>        print(mercedes.returnKilometers())<br>    }<br><br>}</pre><p>I admit that it is not my dream project, though it will be enough to understand the basic concept of unit testing.</p><h3><strong>Creating a test case</strong></h3><p>In order to create a new unit test in iOS:</p><ul><li>From a navigator panel, click UnitTestSampleTests.</li><li>Then click New File…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*AHsObcKcPFeHIu8D4FB4RQ.png" /></figure><p>After that ,you will be taken to another screen, as shown below.</p><ul><li>Select Unit Test Case Class.</li><li>In choose options, type class name: VehicleTests and press Next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hf1lwS4tJwW_GhnuurqAsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V46KF0klcCOkm_xM_pMU2Q.png" /></figure><p>When you click <strong>Next</strong>, you will be taken to another screen. Here you will select where the new VehicleTests file should be created. Make sure you create it in your Unit Tests Group, and also make sure it is only a part of the unit test target, not the app target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPwGEY0h44j0BP-eV8pN8A.png" /></figure><p>With that, we created another test class, although they are actually the same classes that are inheriting from XCTestCase. We will be using VehicleTests to develop our test cases for the vehicle class. You may delete UnitTestSampleTests class as well because we won’t be using it anymore.</p><pre>import XCTest<br><br>class VehicleTests: XCTestCase {<br><br>    override func setUpWithError() throws {<br>        // Put setup code here. This method is called before the invocation of each test method in the class.<br>    }<br><br>    override func tearDownWithError() throws {<br>        // Put teardown code here. This method is called after the invocation of each test method in the class.<br>    }<br><br>    func testExample() throws {<br>        // This is an example of a functional test case.<br>        // Use XCTAssert and related functions to verify your tests produce the correct results.<br>        // Any test you write for XCTest can be annotated as throws and async.<br>        // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.<br>        // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.<br>    }<br><br>    func testPerformanceExample() throws {<br>        // This is an example of a performance test case.<br>        self.measure {<br>            // Put the code you want to measure the time of here.<br>        }<br>    }<br><br>}</pre><h3><strong>Let’s go over vehicle tests class</strong></h3><h4>Use @testable to import your application</h4><p>Since our Vehicle file is not included in our newly created test target, we need to import our main target with @testable. That ensures all code with internal access are available to your test class.</p><pre>import XCTest<br>@testable import UnitTestSample</pre><h4>Declare the properties you want to test</h4><p>We will declare them as <strong>implicitly unwrapped optionals (!)</strong> because by the time our test case has prepared our properties, we verify that they will be initialized and ready to test one another.</p><pre>class VehicleTests: XCTestCase {<br>    <br>    var mercedes: Vehicle!<br>    var boeing: Vehicle!<br><br>}</pre><h4>Override the setUpWithError() method</h4><p>This is a setup method. It lets us initialize variables as needed before each test method is called. Vehicle class will be injected with its corresponding types.</p><pre>override func setUpWithError() throws {<br>        mercedes = Vehicle(type: .Car)<br>        boeing = Vehicle(type: .PassengerAircraft)<br>}</pre><h4>Override the tearDownWithError() method</h4><p>We also want to make sure that we clear everything out when each test finishes running. It lets us clean up variables, set them to nil, etc., after each test method is called.</p><pre>override func tearDownWithError() throws {<br>        mercedes = nil<br>        boeing = nil<br>}</pre><h4>Write a test method</h4><p>If everything is ready, then let’s create our first test method. In this example, we will be comparing our vehicles against each other. In order to demonstrate this comparison we will write a test method that simply verifies a commercial airplane is faster than a car.</p><pre>func testPlaneFasterThanCar() {<br>        //Act<br>        let minutes = 60<br>        <br>        //Arrenge<br>        mercedes.startEngine(minutes: minutes)<br>        boeing.startEngine(minutes: minutes)<br>        <br>        //Assert<br>        XCTAssertTrue(boeing.returnKilometers() &gt; mercedes.returnKilometers())<br>    }</pre><p>Now let’s run the test. Click on the diamond on the left of the function declaration of testPlaneFasterThanCar(). That should run the test. If startEngine(minutes: Int) method which is declared in vehicle class is working as intended, our test result should come back as passed with a green checkmark to signify that the intended test has passed.</p><h4>Async method usage</h4><p>Thus far, we have learned how to develop unit tests and how to access methods written in our main project module. Now, let’s learn how to write a unit test for an async method (ex. network call).</p><p>Add the following code example to the end of VehicleTests:</p><pre>func testFetchPostList() {<br>        let exp = expectation(description:&quot;fetching post list from server&quot;)<br>        let session: URLSession = URLSession(configuration: .default)<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)<br>        guard let customUrl = url else { return }<br>        <br>        session.dataTask(with: customUrl) { data, response, error in<br>            XCTAssertNotNil(data)<br>            exp.fulfill()<br>        }.resume()<br>        waitForExpectations(timeout: 5.0) { (error) in<br>            print(error?.localizedDescription ?? &quot;error&quot;)<br>        }<br>    }</pre><p>Indicated method above verifies that “fetching post list from server” from server returns desired output or else. To control the async method, we used XCTestExpectation as an object. The purpose of using this object is to initialize the expectation first and wait for the intended time until the expectation is fullfilled.</p><p>Alright then, let’s go over the function logic:</p><ol><li>In the first step, we will create<strong> </strong>an<strong> </strong>expectation(description:) that returns an XCTestExpectation object, which of course is stored in exp. The description parameter acts as a descriptor for what you expect to see.</li><li>In the second step, we will call waitForExpectations(timeout:handler:). This method will keep the test running until all created expectations are fulfilled or timeout interval ends (interval is going to execute itself after the indicated number that has been set, e.g. 5.0).</li><li>In the third and the final step, we will call exp.fullfil() if the given result meets our expectations.</li></ol><p>You can also check these links for further information;</p><ul><li><a href="https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations">Asynchronous Tests and Expectations | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/xctest/xctassert">Apple Developer Documentation</a></li></ul><p>The final version of the vehicle test class should look like this:</p><pre>import XCTest<br>@testable import UnitTestSample<br><br>class VehicleTests: XCTestCase {<br>    <br>    var mercedes: Vehicle!<br>    var boeing: Vehicle!<br>    <br>    override func setUpWithError() throws {<br>        // Put setup code here. This method is called before the invocation of each test method in the class.<br>        mercedes = Vehicle(type: .Car)<br>        boeing = Vehicle(type: .PassengerAircraft)<br>      }<br>    <br>    override func tearDownWithError() throws {<br>        // Put teardown code here. This method is called after the invocation of each test method in the class.<br>        mercedes = nil<br>        boeing = nil<br>      }<br>    <br>    func testPlaneFasterThanCar() {<br>        //Act<br>        let minutes = 60<br>        <br>        //Arrenge<br>        mercedes.startEngine(minutes: minutes)<br>        boeing.startEngine(minutes: minutes)<br>        <br>        //Assert<br>        XCTAssertTrue(boeing.returnKilometers() &gt; mercedes.returnKilometers())<br>    }<br><br>    func testFetchPostList() {<br>        let exp = expectation(description:&quot;fetching post list from server&quot;)<br>        let session: URLSession = URLSession(configuration: .default)<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)<br>        guard let customUrl = url else { return }<br>        <br>        session.dataTask(with: customUrl) { data, response, error in<br>            XCTAssertNotNil(data)<br>            exp.fulfill()<br>        }.resume()<br>        waitForExpectations(timeout: 5.0) { (error) in<br>            print(error?.localizedDescription ?? &quot;error&quot;)<br>        }<br>    }<br>}</pre><h4>Conclusion</h4><p>Making a routine of writing unit tests helps us immensely when writing modular pieces of code and assures us that they pass extreme cases as well. Unit tests reduce the possible bugs that may come up in the future while the main codebase is expanding.</p><p>Thank you for reading, and happy coding!</p><p>You can have a look at my code from down below.</p><p><a href="https://github.com/yagizerbay92/UnitTestSample">GitHub - yagizerbay92/UnitTestSample</a></p><p>References:</p><blockquote><a href="https://jasonroell.com/2016/03/10/unit-testing-is-it-worth-it/">https://jasonroell.com/2016/03/10/unit-testing-is-it-worth-it/</a></blockquote><blockquote><a href="https://medium.com/macoclock/how-to-write-unit-tests-in-swift-using-xcode-f59196d0ebc3">https://medium.com/macoclock/how-to-write-unit-tests-in-swift-using-xcode-f59196d0ebc3</a></blockquote><blockquote><a href="https://medium.com/@enricopiovesan/unit-testing-in-swift-tutorial-92daab95246b">https://medium.com/@enricopiovesan/unit-testing-in-swift-tutorial-92daab95246b</a></blockquote><blockquote><a href="https://medium.com/swlh/unit-testing-in-swift-the-fundamentals-eec805766349">https://medium.com/swlh/unit-testing-in-swift-the-fundamentals-eec805766349</a></blockquote><blockquote><a href="https://www.gigacalculator.com/articles/what-is-the-average-speed-of-different-modes-of-transportation/">https://www.gigacalculator.com/articles/what-is-the-average-speed-of-different-modes-of-transportation/</a></blockquote><blockquote><a href="https://www.codecademy.com/article/testing-models-in-swift">https://www.codecademy.com/article/testing-models-in-swift</a></blockquote><blockquote><a href="https://theqalead.com/test-management/unit-testing/">https://theqalead.com/test-management/unit-testing/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1607da61e13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/unit-testing-in-swift-c1607da61e13">Unit Testing in Swift</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>