<?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 Nalydadad on Medium]]></title>
        <description><![CDATA[Stories by Nalydadad on Medium]]></description>
        <link>https://medium.com/@nalydadad?source=rss-a2be70916ca4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bfThPE0ya1l03zkexX2PbA@2x.jpeg</url>
            <title>Stories by Nalydadad on Medium</title>
            <link>https://medium.com/@nalydadad?source=rss-a2be70916ca4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:12:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nalydadad/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[概述 GATT 藍芽傳輸]]></title>
            <link>https://medium.com/@nalydadad/%E6%A6%82%E8%BF%B0-gatt-%E8%97%8D%E8%8A%BD%E5%82%B3%E8%BC%B8-9fa218ce6022?source=rss-a2be70916ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa218ce6022</guid>
            <category><![CDATA[ble]]></category>
            <category><![CDATA[corebluetooth]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[gatt]]></category>
            <category><![CDATA[att]]></category>
            <dc:creator><![CDATA[Nalydadad]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 11:39:26 GMT</pubDate>
            <atom:updated>2019-07-24T11:39:26.341Z</atom:updated>
            <content:encoded><![CDATA[<p>GATT 是 BLE 很基本的傳輸資料方式，透過 Service 跟 Characteristic 的概念，定義傳輸的類型跟內容。市面上幾乎所有 mobile 裝置都支援 BLE，如果需要實作與藍牙周邊裝置溝通的功能，必須對 GATT 有基本了解。此篇就讓我們來釐清這些名詞分別代表什麼意義。</p><h3>在開始前</h3><p>先釐清在 GATT 連線中，Client / Server 的關係：</p><ul><li>藍芽週邊 (Peripheral) 是 GATT Server：掌握 ATT 表，其中包含 services 跟 characteristics 資訊 (稍後會提到)</li><li>Mobile 裝置 (Central) 是 GATT Client：發送 request 到 GATT Server，等待 Peripheral 回傳 Response</li></ul><p>看下圖比較清楚。另外 Peripheral 在沒有配對的情況，會一直廣播(Advertising) 自己的裝置資訊，一旦連線建立後，就會停止 Advertising，因此 Peripheral 只能與一個 Central 建立連線，但 Central 可以與多個 Peripheral 建立連線。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*vwm79UpP94YmZc3Dz7BVVQ.png" /><figcaption>from: <a href="https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all#gatt">https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all#gatt</a></figcaption></figure><h3>GATT (Generic Attribute Profile) 的資料型態</h3><p>由三層資料結構組成：Profile, Service &amp; Characteristic。</p><h4>Profile</h4><p>為一個抽象的概念，代表某個 BLE 週邊裝置提供的所有 Service。我的理解可以視為一個 ATT 表 (後面會說明)</p><h4>Service &amp; Characteristic</h4><p>Service 代表某種功能的資料集合，其中可以包含多個 Characteristic，而 Characteristic 還可以拆解為 property/value 及多個 descriptor，這邊先不多提。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*PDxBYlW8o38_XxNrY-blHg.png" /><figcaption>from: <a href="https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all#gatt">https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all#gatt</a></figcaption></figure><h4>資料實際上長什麼樣子？</h4><p>GATT 利用 ATT 協定儲存上述的 Service 跟 Characteristic。</p><h4>ATT 協定</h4><pre>struct {<br>	u16 uuid;<br>	u8 *data;<br>} att[65536];</pre><p>參考 Source Code，可以知道這個協定就是就是一個 att array 透過 index 查表就可以取出某筆 att 資料 (題外話，在藍牙的世界 index 有個專有名詞叫 handle)。而每筆資料的 UUID 代表 metadata (識別資料類型)，data 代表資料的內容。</p><p>所以存在 ATT 表的 Service 跟 Characteristic 會長的像下圖這樣。每筆資料有可能是一個 Service 或是一個 Characteristic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*mHILshK_sRmJlBqgjXSXRQ.png" /><figcaption>from: <a href="http://lihgong.blogspot.com/2014/10/att-protocol.html">http://lihgong.blogspot.com/2014/10/att-protocol.html</a></figcaption></figure><p>雖說概念上是巢狀的，但是資料卻是連續的。我們要怎麼知道哪些 service 包含哪些 characteristic 呢？</p><p>以上圖為例，其中 service 為 UUID = 0x2800 的資料，我們用此 ID 做切割，就會發現 handle: 0x1、0x8、0x9、0x11、0x15，為 service，而在這之間的資料皆為 characteristic。舉例：handle 0x9 即可以得到在 handle 0x9~0x10 的 characteristics。所以在開發的情境上，如果要透過 GATT 與藍芽裝置溝通，就是在接收 Service 並解析其包含的所有 Characteristic 資料。</p><p>有機會的話，再用 Core Bluetooth 寫個小範例 (一定是幹話… )。</p><h3>參考資料</h3><p><a href="https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all">https://learn.adafruit.com/introduction-to-bluetooth-low-energy?view=all</a></p><p><a href="http://lihgong.blogspot.com/2014/10/att-protocol.html">http://lihgong.blogspot.com/2014/10/att-protocol.html</a></p><p><a href="http://lihgong.blogspot.com/2014/10/gatt-protocol.html">http://lihgong.blogspot.com/2014/10/gatt-protocol.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa218ce6022" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WWDC 2019 筆記連載（2） —  [216] SwiftUI Essentials]]></title>
            <link>https://medium.com/@nalydadad/wwdc-2019-%E7%AD%86%E8%A8%98%E9%80%A3%E8%BC%89-2-216-swiftui-essentials-aed83b0e6e2e?source=rss-a2be70916ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed83b0e6e2e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[wwdc-2019]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Nalydadad]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 14:03:58 GMT</pubDate>
            <atom:updated>2019-06-12T14:04:41.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>WWDC 2019 筆記連載(2) — [216] SwiftUI Essentials</h3><h3>大綱</h3><p>本 Session 重點放在介紹 SwiftUI 基本語法的使用。講者分成幾個部分說明</p><ol><li>Views and Modifiers: 相關 Syntax 解說</li><li>Building custom views: 示範客製化 View</li><li>Composing Controls: 示範使用 Control</li><li>Navigating your app: 示範實作類似 Navigation Controller 的 UI</li></ol><h3>看點</h3><p>前面的 Syntax 講解個人認為很重要，有一種觀念一層一層被搭上來的感覺。看不懂的地方可以搭配 Document 服用</p><h3>筆記</h3><p>重點部分著重於 Syntax，可以分成幾個部分說明。其餘示範帶過了幾個基本的 Primitive Views，但我覺得這個階段知道這些還不是很重要，所以我也只會稍微帶過一下。分成幾個部分說明：</p><ol><li>View Container Syntax</li><li>Binding Syntax</li><li>Modifier</li><li>Views 及 Controls 實例</li></ol><h3>1. View Container Syntax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*OvF53G60_Vf3N6hqn9Ir9g.png" /><figcaption>View Container Syntax</figcaption></figure><p>大家都應該知道 View Container Syntax 長這樣，不過我們來探討一下為什麼，舉 VStack 為例，我們可能會這樣寫：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g60uXG64CLH0imm5hFfx8A.png" /><figcaption>VStack Example</figcaption></figure><p>再來看一下其建構子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DovjrNpLzYqlNGwNE199jw.png" /><figcaption>VStack Constructor</figcaption></figure><p>看起來所有的 Primitive View 都會提供 content callback 這個介面，讓我們實作。但你一定覺得很奇怪，我宣告這麼多 View 沒有回傳，也沒有動作，View 是怎麼 build 起來的。</p><h4>@ ViewBuilder</h4><p>這時候就要注意到 ViewBuilder。它是 Swift 5.1 的語法，專業術語叫作 <a href="https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5e0ea20bee98657d93902d5b174/proposals/XXXX-function-builders.md">Function Builders</a> 要深究的可以參考 swift evolution 的說明。簡單來說就是每一行我們實作的 buildBlock，例如 Text(“Hello World”)，隨後會被合併到 <a href="https://developer.apple.com/documentation/swiftui/viewbuilder">ViewBuilder</a> 根據一些條件循序的 build 各個 buildBlock。可以參考<a href="https://onevcat.com/2019/06/swift-ui-firstlook/">貓大的 blog</a> 有詳細說明背後實作</p><h4>some 語法</h4><p>另外一個令人困惑的就是 some 了。它是 Swift 5.1 的 Opaque Types 語法。簡單來說使用 some 的好處是能保存 Protocol 抽象的特性，也就是 concrete type 不會被暴露，但卻在 compile time 就能指定好實體，不會增加 runtime 的 loading。但要注意的是因為用了 some 語法，所以在 compile time 必須決定類型的實體，所以不能回傳不同類型的 View，例如 If 回傳 Text else 回傳 Button，這樣是不允許的。同樣建議參考<a href="https://onevcat.com/2019/06/swift-ui-firstlook/">貓大的 blog</a> 有詳細說明。</p><h3>2. Binding Syntax</h3><p><strong>@ State</strong> 跟 $</p><p>如果 UI 的狀態需觀察資料改變化，變數宣告時需加上 <strong>@ State</strong> 修飾，使用時需加上 $ 前綴。當變數被宣告為 <strong>@ State 時</strong>，SwiftUI 會管理其記憶體，當 property 被更新時，UI 會 invalidate 再 update。且此變數應該宣告為 private，因為它的作用就像是 function 的 persistent value 一樣，只能在 View 中被存取。詳細內容可能需要看完 [226] Data Flow Through SwiftUI 再深入了解。</p><h3>3. Modifier</h3><p>第一次認識 Modifier 時，只知道是用來修飾 View 的 Function，但沒有仔細想清楚，其實每次呼叫一個 Modifier 都會回傳新的 View，可能帶來效能上的疑慮，不過講者馬上補充道 “Render Engine 本身會解決 Modifier Chain 帶來的效能問題”。值得注意的是，它提到了 <strong>Modifier Chain</strong> 讓我想到 Modifier 是有順序性的，放在不同的順序可能會帶來不同的 layout 效果。除此之外，講者也介紹了 <strong>Modifier Sharing</strong> 的概念，也就是對某一層 View 呼叫 Modifier，此階層下的所有 SubViews 都能夠套用該 Modifier。</p><h3>4. Views 及 Controls 實例</h3><p>這邊就列舉我聽到的一些細節：</p><ul><li>當 View 從 View Hierarchy 增刪的時候，SwiftUI 會自帶 Fade-In Fade-Out 的效果</li><li>List binding 的 Data 若有變動的時候，SwiftUI 會自動 Diff 並做出像是 UITableView 增刪的動畫。</li><li>List 及 ForEach 可以做到一樣的效果，但 ForEach 就不會有前述或是一些隱晦的 render 行為</li><li>同理 Form 及 VStack 視覺上可以做到一樣的效果，但 Form 有一些 Default 的 render 行為</li><li>Picker 可以列舉 Enum</li><li>介紹 @ Environment，可以用此 Modifier 模擬不同環境的 Preview，- 諸如：Dynamic Size、Dark Mode、Right-to-Left layout direction…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10FujfRv3TKnK4a-4op3Gw.png" /></figure><ul><li>NavigationView、NavigationButton、SplitView 及 TabbedView 的使用。先不多做說明。</li></ul><h3>下一篇會看</h3><p>[226] Data Flow Through SwiftUI</p><h3>參考資料</h3><ul><li><a href="https://developer.apple.com/wwdc19/216">https://developer.apple.com/wwdc19/216</a></li><li><a href="https://onevcat.com/2019/06/swift-ui-firstlook/">https://onevcat.com/2019/06/swift-ui-firstlook/</a></li><li><a href="https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5e0ea20bee98657d93902d5b174/proposals/XXXX-function-builders.md">https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2Fapple%2Fswift-evolution%2Fblob%2F9992cf3c11c2d5e0ea20bee98657d93902d5b174%2Fproposals%2FXXXX-function-builders.md</a></li><li><a href="https://developer.apple.com/documentation/swiftui/viewbuilder">https://medium.com/r/?url=https%3A%2F%2Fdeveloper.apple.com%2Fdocumentation%2Fswiftui%2Fviewbuilder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed83b0e6e2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WWDC 2019 筆記連載 — [ 204 ] Introducing SwiftUI: Build Your First App]]></title>
            <link>https://medium.com/@nalydadad/wwdc-2019-%E7%AD%86%E8%A8%98%E9%80%A3%E8%BC%89-204-introducing-swiftui-build-your-first-app-3d3c6753e158?source=rss-a2be70916ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d3c6753e158</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[wwdc-2019]]></category>
            <dc:creator><![CDATA[Nalydadad]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 14:49:14 GMT</pubDate>
            <atom:updated>2019-06-12T14:05:11.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>WWDC 2019 筆記連載(1) — [ 204 ] Introducing SwiftUI: Build Your First App</h3><blockquote>SwiftUI 中間沒有空格</blockquote><h3>大綱</h3><p>示範如何用 SwiftUI 實作相當於 UIKit 中 UITableViewController 的 View。</p><h3>看點</h3><ol><li>如何從 0 開始使用 SwiftUI Framework</li><li>當講者把 View 包在 List 的時候，我覺得掀起了一波高潮，有興趣的可以看 Demo。接著開始各種 SwiftUI 技巧，這才是現代的 Layout 啊！</li></ol><h3>筆記</h3><p>這個 session 算是一個 SwiftUI 的 Get Started，大概可以聞出 SwiftUI 的味道，原理就是讓想要客製化的 View Object conform View Protocol，所有需要更新 UI 的時機，系統都會呼叫此 protocol 的 var body: Self.Body { get } 更新畫面。所以把所有 layout 邏輯放在裡面就對了。</p><p>SwiftUI 的各個元件都是 Struct，並且 Framework 提供許多修飾 UI 元件的 function，官方稱之 Modifier。Xcode 11 為 SwiftUI 提供許多新功能，不僅可以 Preview，還可以 Drag and drop UI 元件及修飾元件的 Modifier 到 Preview 畫面上新增設定，同時自動產生對應的 code。另外這種 layout 方式會有一個缺點，就是 Nested Code，Xcode 也提供 Extract SubView 的功能，解決此問題，（希望這個功能不要太卡 main thread 啊…）官方宣稱 Extract SubView 不會有 runtime 效能的問題，應該是早就 compile 好了。</p><p>看完解說還蠻好上手的，就跟剛學 iOS 一樣，第一個要學會的就是如何實作 UITableViewController。SwiftUI 使用 List 搭配 NavigationButton 就可以有此效果，編輯模式的設定更是加上幾個 modifier 就搞定，省去了許多 Delegate 的設定。聽起來容易，但一些更細節的狀態更新，還需要更深入研究。</p><h3>其他</h3><ul><li>筆記提到的 “需要更新 UI 的時機” 值得深究，以此 Demo 來說提到兩個例子: 1.@State Property 改變時 2.@ObjectBinding</li><li>SwiftUI 不用處理 Autolayout，所以應該有寫 Render Engine 的細節還沒了解到</li><li>內容有提到 Data Flow 的概念，在 [226] Data Flow Through SwiftUI 會再深入探討</li></ul><h3>參考資料</h3><ul><li><a href="https://developer.apple.com/wwdc19/204">https://developer.apple.com/wwdc19/204</a></li><li><a href="https://developer.apple.com/documentation/swiftui/views_and_controls">https://developer.apple.com/documentation/swiftui/views_and_controls</a></li></ul><h3>下一篇要看</h3><p>[216] SwiftUI Essentials</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d3c6753e158" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift：Mutating Function.]]></title>
            <link>https://medium.com/@nalydadad/swift-mutating-function-b0a8c02b616b?source=rss-a2be70916ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a8c02b616b</guid>
            <category><![CDATA[mutating]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Nalydadad]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 15:56:47 GMT</pubDate>
            <atom:updated>2019-01-26T01:54:04.602Z</atom:updated>
            <content:encoded><![CDATA[<p>當 Value Type 的 Instance method 改變自己的值時，該 function 要用 mutating 修飾。先舉個錯誤的例子：</p><pre>struct Stack {<br>    var elements = [Int]()<br>    func pop() -&gt; Int {<br>        return elments.removeLast()<br>    }<br>    <br>    func push(element: Int) {<br>        elements.append(element)<br>    }<br>}</pre><p>上述例子中，pop()、push() 皆改變了 elements 的值，因此需加上 mutating，否則會有 compiler error。正確範例如下：</p><pre>struct Stack {<br>    var elements = [Int]()<br>    mutating func pop() -&gt; Int {<br>        return elments.removeLast()<br>    }<br>    <br>    mutating func push(element: Int) {<br>        elements.append(element)<br>    }<br>}</pre><p>另外，在 mutating function 中也可以 assign 新的 instance 給自己。</p><pre>struct Point {<br>    var x = 0<br>    var y = 0<br>    mutating func reset() {<br>        self = Point(x: 0, y: 0)<br>    }<br>}</pre><p>但有沒有想過為什麼需要有 mutating 這樣的設計？function 內改就改了，幹嘛那麼囉嗦？</p><p>延續剛剛宣告的 Point，我們來看下面的例子，使用 let 來宣告一個 Point，並操作 mutating function：</p><pre>let point = Point(x: 10, y:10)<br>point.reset()</pre><p>這樣寫 compiler 是會報錯的：<strong>Cannot use mutating member on immutable value: ‘point’ is a ‘let’ const</strong>。此時把 let 改成 var：</p><pre>var point = Point(x: 10, y:10)<br>point.reset()</pre><p>compiler 就接受了，為什麼？</p><h4>我們來推理看看…</h4><p>首先，宣告 let 所以 immutable，不能操作 mutating 合理。而宣告 var 代表可變的，所以操作 mutating 合理。但等等，我們忘了一個重要的觀念，<strong>Value Type 不是本來就是 immutable 的嗎？</strong></p><p>沒錯，所以每當 Value Type 被宣告成 var 時，實際上所有的改動都是 copy 一個新的 value 到原本宣告的變數。同理， mutating function 也是在做一樣的事情。我們可以理解成 swift 讓我們寫了一個很明顯的 mutating 標籤，來限制 immutable 的型態不能用 mutating，而當有改動的時候，就會觸發 copy 的行為。這樣應該更了解，為什麼 compiler 會限制你一定要寫 mutating 了吧？</p><h4>結論</h4><ul><li>Value Type 自己的 Instance method 改變了自己的值時，需加上 mutating</li><li>Value Type 是 immutable 的，所以任何 assign 都會觸發 copy。同理，mutating function 也會觸發 copy（btw. swift 有一個有效率的 copy 機制叫作 copy-on-write）</li><li>Reference Type 是沒有 mutating function 的，寫了會被 compiler 抱怨。</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a8c02b616b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[關於 單元測試]]></title>
            <link>https://medium.com/ios-nerd/%E9%97%9C%E6%96%BC-%E5%96%AE%E5%85%83%E6%B8%AC%E8%A9%A6-937ea5172539?source=rss-a2be70916ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/937ea5172539</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nalydadad]]></dc:creator>
            <pubDate>Sun, 08 Apr 2018 13:10:37 GMT</pubDate>
            <atom:updated>2018-04-10T02:19:58.968Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在準備有關單元測試的簡報，有感而發，來談談我所認知的單元測試，以及我認為對一個軟體工程師來說，單元測試所需最基本的認知。今天不討論程式碼，純粹分享一些想法及概念。</p><h4>“單元測試” 是什麼？</h4><p>測試程式裡面可執行的最小單元，即為單元測試。而程式裡面最小可執行的單元為方法（function），所以單元測試是在測試方法的行為是否符合預期。除此之外，在物件導向的世界中，我們通常測試的目標會是一個類別（class），透過測試類別的行為，我們會產生一個測試套件，將這些測試案例（test case）放在測試套件（test suite）中，由此脈絡你可以很清楚的了解，你平常看到的單元測試是用什麼樣的一個邏輯設計出來的。</p><h4>為什麼需要單元測試？</h4><p>當然是買保險啊！第一次聽到這個名詞，應該都是這個反應，又或許你的腦海中已經浮現出許多答案。但我第一次對於買保險這個想法，其實是充滿疑問的， “單元測試也是人寫出來的程式碼，既然人寫出來的程式碼會有問題，為什麼要自己寫程式碼來測試自己的程式碼？”</p><p>現在想想覺得蠻有趣的，或許有人有一樣的疑惑，但我要以這段話來支持我的論點。既然你寫的單元測試也有可能出錯，那一定在測試的時候會反映出來，所以不需害怕測試程式碼讓你的測試失敗，應當仔細檢視失敗原因，且提交的時候，一定要確保所有的單元測試都是成功的，這樣才真正是一個保險。</p><p>它是一個保險，它能防守未來的你或一起共事的同事在重構或改動程式碼的時候不出錯。它也是一個 Spec，在設計測試案例的時候，同時在擬定這個類別應當有的行為，當你提交這段程式碼時，測試案例就是你所訂定的標準。</p><p>講到這就一定要提到之前同事常舉的例子。有一次他要使用某個第三方的 Framework，但官方文件看來看去都不知道怎麼使用，最後他從 Framework 的測試案例裡才學會如何使用。</p><h4>掌握 3A 原則、一次只測一個行為</h4><p>測試案例必須由三個部分組成， <strong>Arrange</strong>、<strong>Act</strong>、<strong>Assert</strong> ，就像是寫作文的起承轉合一樣。<strong>Arrange</strong> 描述這個受測目標的前置準備（生成物件）需有什麼條件；<strong>Act</strong> 描述要做什麼動作；以及 <strong>Assert</strong> 預期要有什麼行為。掌握這個思路，寫單元測試才會完整。測試程式的可讀性才會高，是為將來的你或是一起工作的同事提高維護的便利性。</p><p>除此之外，也請謹守一次只測試一個行為的原則。 就像是以前在實驗課學到的，必須確保實驗組及對照組的操縱變因只有一個，當測試不通過時，便能快速發現問題的根源，而不需要再做另外的測試。</p><p>謹守這兩個原則，你就可以開始撰寫簡單的單元測試。</p><h4>解決相依性</h4><p>當你開始寫單元測試，你可能會發現你寫不下去。在 Arrange 的階段，要準備的參數，就讓你千頭萬緒理不清。原本在設計的時候，過多的相依性，在這個時候將會全部糾結在一起，成為你的絆腳石。</p><p>這是不是也點出一個寫測試的好處？為了讓類別可以被測試（testable），我們更需在類別設計階段，仔細檢視類別之間的相依性，思考清楚類別之間的權責，以及開口（造成相依的原因）的設計。</p><p>除此之外，也有一些解決相依問題的 Pattern （Stub、Mock、Fake），雖然不在我們今天的討論範圍，但都是解決相依性的好方法。</p><p>在測試的過程，我有一個心法。我會把待測試物件想像成一顆心臟，當一顆心臟從身體拔出時，我要如何讓他繼續跳動，我必須把左心房以及右心房接上我自己模擬的假動脈，把左心室及右心室接上模擬的假靜脈，用幫浦打血液進假動脈，並測試假靜脈是否正常流出血液。這就是我如何讓原本相依的元件抽離的心法。</p><h4>我要測到什麼程度？覆蓋率重要嗎？private 方法要測嗎？</h4><p>回想一下你寫單元測試的初衷，一定是要確保你提交出去的程式碼保有你預期的行為，所以你才會在測試程式中 “插了許多眼” 。這樣答案是否就呼之欲出了，如果是你想要確保的行為，你是否就應該為它寫測試？</p><p>至於覆蓋率重要嗎？我覺得重質不重量，覆蓋率是要到一定的比例，代表你為這個類別大部分的程式碼提出擔保，但不一定要為了提高覆蓋率而走火入魔，我的做法其實是我不會特別注意覆蓋率，但我一定確保所有 public 方法都有被測到，或許你也可以以這為標準。同時也間接回應了第三個問題，反之 private 方法我不會測，因為既然它是 private，在類別內部的運作中，它必然會被呼叫到，所以執行了 public 方法，也同時在確保 private 方法不會 crash。</p><h4>結論</h4><p>我覺得寫單元測試是 Z&gt;B，在開發階段，可以確保自己的設計邏輯正確，可以讓設計的架構清楚（至少耦合度較低），且為將來的自己準備好描述文件，甚至將來要改動這段程式碼時，有一個保障。當然有人會質疑，在開發階段是否會花更多的時間，而拖慢開發速度？我的答案是一定會，但會減少解 bug 的量及時間，讓程式更加穩定，當你熟悉且有良好習慣的時候絕對是能增加開發速度的。</p><p>不管在看這篇文章的你對於單元測試原本抱持什麼樣的立場，但希望這篇簡單的分享，有增加想要寫單元測試的動力，自己的程式碼品質自己救。希望看完此篇文章，對你有一些好的衝擊，也歡迎一起討論。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=937ea5172539" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nerd/%E9%97%9C%E6%96%BC-%E5%96%AE%E5%85%83%E6%B8%AC%E8%A9%A6-937ea5172539">關於 單元測試</a> was originally published in <a href="https://medium.com/ios-nerd">iOS Nerd 🤓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>