Jiazheng Shen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    - Book mode https://hackmd.io/@ncnu-opensource/book # Week 06 (2025/03/27) 自動測試、大量部署 :::success **Interface vs class** interface 只描述有哪些**方法(Method)**,但不用寫出具體的行為。 ```java= interface Animal { void makeSound(); } ``` - 沒有方法的實作,所有方法都是抽象(abstract)的。 要使用再透過 class 來實作它就好,留給不同的 class 來決定 method ```java= class Dog implements Animal { public void makeSound() { System.out.println("Woof!"); } } class Cat implements Animal { public void makeSound() { System.out.println("Meow!"); } } ``` ::: --- ## 自動化測試 ### 常見測試替身(Stub、Mock、Spy) #### Stub - 當要驗證的 function 需要第三方的回傳資料(沒有帶參數),就製作假資料取代第三方的回傳資料 - ex. call DB data :::success 所謂的 Third-Party Function(第三方函式),指的是你的程式碼沒有直接控制的外部函式,通常來自第三方服務或函式庫。例如: - 外部 API(如 Google Maps API) - 雲端服務(如 AWS S3、Firebase) - 資料庫查詢(如 SqlConnection.Query()) - 郵件發送服務(如 SmtpClient.SendMail()、SendGrid.SendEmail()) ::: - 實際方法 - 用 dependency injection 的寫法,把會使用到的第三方物件帶入 class - 測試時再將帶入的第三方物件改為自己設定的 - ![](https://hackmd.io/_uploads/Hyr93P8gp.png) - EmailSystem 裡的 JJEmailService.SendEmail() 就屬於 Third-Party Function,因為它來自 JJEmail 套件(假設這是第三方函式庫),你的程式碼只是呼叫它,而不能改變它的行為。 - ![](https://hackmd.io/_uploads/Sk9unP8gp.png) :::info **Dependency Injection**(依賴注入): 是一種程式設計模式,用來將物件所依賴的資源(例如:服務、資料庫、API 等)從外部傳進來,而不是在物件裡面自己建立。 可降低「耦合度」,且會更容易測試(ex:在測試時注入 Stub 或 Mock 來取代真實物件。 ::: --- # 供鯊小!?,看不懂可以往下 我們用 **USB-C** 的比喻來解釋 **Dependency Injection(DI,依賴注入)** ## **🔌 USB-C vs Dependency Injection** **過去的情況(沒有 DI,依賴具體類別)** - 以前各種設備使用 **不同的充電接頭**(USB-A、Micro-B、Lightning...)。 - 你買了一條 **特定的線材**,只能用在某些設備上,換設備時可能還得換線材(**強耦合**)。 - 如果有新標準出現(例如 USB PD 快充),舊設備 **可能不支援**,你得換整套充電器和線材(**難以擴充**)。 **現在的情況(使用 DI,依賴抽象)** - **USB-C 是統一的接口**,但可以搭配不同的**協議**(PD 充電、DisplayPort、Thunderbolt...)。 - 你不需要直接決定設備的充電方式,而是**根據需求插上不同的線材**(DI 的「注入」)。 - **筆電、手機、顯示器都可以共用相同的 Type-C 接口**,但功能可能不同(不同 `class` 的 `implements`)。 - **當新技術出現時**(例如更快的充電協議),你**只需要換充電器或線材,而不用換設備本身**(低耦合、可擴展)。 --- ## **🔧 在程式中如何對應?** ### **沒有 DI(硬性綁定,像是固定 USB-A、Micro-B)** ```java class Laptop { private UsbACharger charger; // 直接依賴具體類別 public Laptop() { this.charger = new UsbACharger(); // 內部建立,無法替換 } public void charge() { charger.supplyPower(); } } ``` 🔹 **問題:** - `Laptop` 只能用 `UsbACharger`,如果要換成 `UsbCCharger`,就要修改 `Laptop` 的程式碼。 - **高耦合**,不易擴展。 --- ### **有 DI(使用 `interface`,像是 USB-C 插座,可插不同線材)** ```java interface Charger { void supplyPower(); } // 定義不同的充電方式 class UsbACharger implements Charger { public void supplyPower() { System.out.println("Charging with USB-A."); } } class UsbCCharger implements Charger { public void supplyPower() { System.out.println("Charging with USB-C."); } } // Laptop 不直接依賴具體類別,而是依賴介面(Charger) class Laptop { private Charger charger; // 透過 DI 注入不同的 Charger public Laptop(Charger charger) { this.charger = charger; } public void charge() { charger.supplyPower(); } } public class Main { public static void main(String[] args) { Charger usbA = new UsbACharger(); Charger usbC = new UsbCCharger(); // 隨時替換不同的充電方式 Laptop myLaptop = new Laptop(usbC); myLaptop.charge(); // Charging with USB-C. } } ``` 🔹 **優勢:** - `Laptop` **不再直接依賴** 具體類別,而是依賴 `Charger`(**抽象介面**)。 - **可以隨時替換不同充電方式**,不用改 `Laptop` 本身(**低耦合、可擴展**)。 - **如果有新的充電標準(如 GaN 充電器)**,只要新增一個 `GanCharger implements Charger`,就能直接使用! --- ## **🛠 總結** **🔌 USB-C vs Dependency Injection** | USB-C | Dependency Injection | |-------|----------------------| | **不同設備共用相同的 Type-C 接口** | **不同類別共用相同的 `interface`** | | **可根據需求更換充電器、線材** | **可根據需求更換 `class` 的 `implements`** | | **新標準(PD、DP、Thunderbolt)可以直接支援** | **新功能可以通過新增 `class` 擴展,而不影響舊有程式** | | **低耦合(設備不綁定特定接頭)** | **低耦合(`class` 不綁定特定 `implements`)** | --- # 回頭看 EmailSystem, IEmailService, JJEmailService 我們可以把 **EmailSystem、IEmailService、JJEmailService** 這些元素對應到 **USB-C 比喻** 中的不同對象,這樣會更清楚它們的關係! ## **🔌 對應關係** | 程式設計對象 | USB-C 比喻 | |-------------|-----------| | `IEmailService`(介面) | **USB-C 插座(統一標準)** | | `JJEmailService`(具體類別) | **特定的 USB-C 充電器(不同實作)** | | `EmailSystem`(使用者) | **筆電、手機(需要充電的設備)** | | `SendEmail()`(方法) | **充電協議(PD、QC、Thunderbolt...)** | --- ## **🔍 具體比喻** 1. **`IEmailService` 是 `interface`(抽象標準)** - 它就像 **USB-C 插座**,**定義了一個統一標準**,但不決定具體怎麼充電(發送 Email)。 - 任何**想要發送 Email 的系統**(比如 `EmailSystem`),都會透過這個標準來使用 Email 服務。 - 例如: ```java interface IEmailService { String SendEmail(String mailAddress, String mailMessage); } ``` 2. **`JJEmailService` 是 `IEmailService` 的具體實作** - 它就像 **USB-C 充電器**,有不同的規格(PD 充電、Thunderbolt)。 - 例如 `JJEmailService` 可能使用 AWS SES,而另一個 `GmailEmailService` 可能用 Gmail API,**它們的外部行為相同,但內部實作不同**。 - 例如: ```java class JJEmailService implements IEmailService { public String SendEmail(String mailAddress, String mailMessage) { System.out.println("Sending email using JJEmailService..."); return "Success"; } } ``` 3. **`EmailSystem` 透過 DI 使用 `IEmailService`(依賴抽象,而非具體類別)** - `EmailSystem` 代表 **筆電或手機**,它只管「**我要發送 Email(我要充電)**」,但不關心 **具體怎麼發送(具體怎麼充電)**。 - `EmailSystem` 只認 `IEmailService`,不直接認 `JJEmailService`,所以可以靈活替換不同的 Email 服務(像是換不同的充電器)。 - 例如: ```java class EmailSystem { private IEmailService emailService; // 依賴抽象,不直接耦合具體類別 public EmailSystem(IEmailService emailService) { this.emailService = emailService; } public String EmailFunction(String mailAddress, String mailMessage) { return emailService.SendEmail(mailAddress, mailMessage); } } ``` 4. **使用時透過 Dependency Injection 注入不同的 Email 服務** - 這就像你可以用 **不同品牌的 USB-C 充電器** 來充筆電,筆電本身不需要修改。 - 例如: ```java public class Main { public static void main(String[] args) { IEmailService emailService = new JJEmailService(); // 換成不同服務時,只要改這一行 EmailSystem emailSystem = new EmailSystem(emailService); emailSystem.EmailFunction("user@example.com", "Hello World!"); } } ``` - **換 Gmail API 服務時,只要換一個新的 `GmailEmailService`,不需要改 `EmailSystem`!** ```java IEmailService emailService = new GmailEmailService(); ``` --- ## **🎯 為什麼這樣設計比較好?** - **降低耦合(Low Coupling)**:`EmailSystem` 只依賴 `IEmailService`,不綁定特定的 `JJEmailService`,未來可以輕鬆換不同的 Email 服務(AWS SES、Gmail API…)。 - **靈活擴展(Scalability)**:當有新技術(新 Email 服務、USB-C 新規格)時,只要加一個 `class`,不用改 `EmailSystem`(筆電不需要重新設計)。 - **更容易測試(Testability)**:我們可以建立一個 `StubEmailService` 來模擬發送 Email,而不真的發信(像是測試充電功能時,不真的插電)。 --- ## **🛠 總結** - **`IEmailService` = USB-C 插座(標準化介面)** - **`JJEmailService` = USB-C 充電器(具體實作)** - **`EmailSystem` = 筆電/手機(使用 Email 服務的對象)** - **`SendEmail()` = 充電協議(PD, QC, Thunderbolt)** - **`Dependency Injection` = 更換不同的充電器,而不影響筆電本身** 這樣的設計讓 `EmailSystem` 可以靈活切換不同的 Email 服務,就像筆電能自由選擇不同的 USB-C 充電器一樣! 🚀 --- # 接著解釋常見測試替身(Stub、Mock、Spy) 我們可以沿用 **USB-C** 的比喻來解釋 **Stub、Mock、Spy** 這些常見的測試替身(Test Doubles),這樣會更容易理解它們的作用! ## **🔌 先回顧主要對應** | 程式設計對象 | USB-C 比喻 | |-------------|-----------| | `IEmailService`(介面) | **USB-C 插座(標準化接口)** | | `JJEmailService`(具體類別) | **特定的 USB-C 充電器(不同品牌的實作)** | | `EmailSystem`(使用者) | **筆電、手機(需要充電的設備)** | | `SendEmail()`(方法) | **充電協議(PD、QC、Thunderbolt...)** | --- ## **📌 什麼是 Stub、Mock、Spy?** 當我們測試 `EmailSystem` 時,真實的 `JJEmailService` 可能會發送真實 Email(像是真的插上充電器供電)。但我們通常不希望測試時真的發送 Email,這時候我們就可以使用「測試替身(Test Doubles)」來模擬 Email 服務的行為,讓測試更有效率、更可控。 ### **1️⃣ Stub(測試假物)** **🔹 定義:** - **Stub 只是返回固定的結果**,不會有額外的邏輯或記錄。 - 只用來提供預期的輸出,而不會模擬行為。 **🔌 USB-C 比喻:** - **Stub 就像一個「假電流測試器」**,只要插上 USB-C,它就回應「OK!電流正常!」,但其實它不會真的充電。 **📝 在測試中:** - 當 `EmailSystem` 呼叫 `SendEmail()`,Stub 會直接回傳 `"Success"`,但不會真的發送 Email。 **✅ 例子(Java)** ```java class StubEmailService implements IEmailService { @Override public String SendEmail(String mailAddress, String mailMessage) { return "Success"; // 只返回固定值 } } ``` **🔬 測試** ```java public class EmailSystemTest { public static void main(String[] args) { IEmailService stubService = new StubEmailService(); EmailSystem emailSystem = new EmailSystem(stubService); String result = emailSystem.EmailFunction("test@example.com", "Hello"); System.out.println(result); // Output: Success } } ``` --- ### **2️⃣ Mock(模擬物件)** **🔹 定義:** - **Mock 會驗證「某個方法是否被呼叫」**,但不會真的執行行為。 - 會「記錄」測試時發生的事情,讓我們檢查**是否正確地與外部系統互動**。 **🔌 USB-C 比喻:** - **Mock 就像一個 USB 測試儀**,它不會真的供電,但它會記錄 **「這台筆電有沒有嘗試充電?」、「用了多少電壓?」** - 我們可以在測試後檢查:「筆電有沒有要求充電?」(驗證 `SendEmail()` 是否被呼叫) **✅ 例子(使用 Mockito)** ```java import static org.mockito.Mockito.*; public class EmailSystemTest { public static void main(String[] args) { // 建立 Mock 物件 IEmailService mockService = mock(IEmailService.class); // 設定當 SendEmail 被呼叫時回傳 "Success" when(mockService.SendEmail(anyString(), anyString())).thenReturn("Success"); EmailSystem emailSystem = new EmailSystem(mockService); emailSystem.EmailFunction("test@example.com", "Hello"); // 驗證 SendEmail() 是否被呼叫一次 verify(mockService, times(1)).SendEmail("test@example.com", "Hello"); } } ``` **🧐 測試會檢查** - `SendEmail()` 是否有被呼叫? - `SendEmail()` 被呼叫幾次? - `SendEmail()` 被呼叫時,參數是否正確? --- ### **3️⃣ Spy(間諜物件)** **🔹 定義:** - **Spy 會「部分使用真實的行為」,但同時記錄發生了什麼事。** - 它不像 Stub 只回傳固定值,也不像 Mock 只是記錄,它**可以真正執行部分邏輯,但仍然可以驗證行為**。 **🔌 USB-C 比喻:** - **Spy 就像一個智慧型 USB-C 充電器,它真的會充電,但它同時也會記錄「充電多少時間?」、「消耗多少瓦數?」** - 它既能提供「真的充電行為」,也能回頭檢查充電過程中的數據。 **✅ 例子(使用 Mockito)** ```java public class SpyEmailService implements IEmailService { private int emailSentCount = 0; @Override public String SendEmail(String mailAddress, String mailMessage) { emailSentCount++; // 記錄發送次數 return "Success"; } public int getEmailSentCount() { return emailSentCount; } } // 測試 Spy public class EmailSystemTest { public static void main(String[] args) { SpyEmailService spyService = new SpyEmailService(); EmailSystem emailSystem = new EmailSystem(spyService); emailSystem.EmailFunction("test@example.com", "Hello"); emailSystem.EmailFunction("test2@example.com", "Hi"); System.out.println("Emails sent: " + spyService.getEmailSentCount()); // Output: 2 } } ``` **🧐 測試會檢查** - `SendEmail()` **真的有執行**。 - `Spy` 可以記錄 `SendEmail()` 被呼叫的次數,確保 EmailSystem 確實有發送 Email。 --- ## **🔬 總結** | 測試替身 | 定義 | USB-C 比喻 | 何時使用? | |----------|------|-----------|-----------| | **Stub** | **回傳固定值**,但不執行任何邏輯 | **假電流測試器,只顯示「OK!」,但不充電** | 當你只想要一個簡單的回應,而不需要記錄或驗證時 | | **Mock** | **不執行行為,但記錄是否被呼叫** | **USB 測試儀,記錄「充電多少電壓?」但不充電** | 你只想測試 **某個方法是否有被呼叫**,不關心具體執行 | | **Spy** | **部分執行行為,同時記錄數據** | **智慧型充電器,真的充電,並記錄充電數據** | 你想要**執行真實行為,同時記錄資訊** | --- ## **🚀 結論** - **`EmailSystem`** = 筆電,想要發送 Email(需要充電)。 - **`IEmailService`** = USB-C 接口,定義標準(統一的 `SendEmail()` 方法)。 - **`JJEmailService`** = 真正的 Email 服務(AWS SES、Gmail API,對應不同品牌的充電器)。 - **Stub、Mock、Spy** = 測試替身,就像不同類型的 USB 測試儀。 這樣你應該能夠更清楚 **Stub、Mock、Spy** 的用途了 # Ref. https://medium.com/wenchin-rolls-around/%E6%B7%BA%E5%85%A5%E6%B7%BA%E5%87%BA-dependency-injection-ea672ba033ca

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully