編寫“單元測試”代碼? (Writing "unit testable" code?)


問題描述

編寫“單元測試”代碼? (Writing "unit testable" code?)

What kind of practices do you use to make your code more unit testing friendly?


參考解法

方法 1:

  • TDD -- write the tests first, forces you to think about testability and helps write the code that is actually needed, not what you think you may need

  • Refactoring to interfaces -- makes mocking easier

  • Public methods virtual if not using interfaces -- makes mocking easier

  • Dependency injection -- makes mocking easier

  • Smaller, more targeted methods -- tests are more focused, easier to write

  • Avoidance of static classes

  • Avoid singletons, except where necessary

  • Avoid sealed classes

方法 2:

Dependency injection seems to help.

方法 3:

Write the tests first - that way, the tests drive your design.

方法 4:

  1. Use TDD
  2. When writing you code, utilise dependency injection wherever possible
  3. Program to interfaces, not concrete classes, so you can substitute mock implementations.

方法 5:

Make sure all of your classes follow the Single Responsibility Principle. Single responsibility means that each class should have one and only one responsibility. That makes unit testing much easier.

(by TWAtvanfossondss539Shane FulmerPaulJWilliamsRobert Cartaino)

參考文件

  1. Writing "unit testable" code? (CC BY-SA 3.0/4.0)

#automated-tests #unit-testing #language-agnostic






相關問題

編寫“單元測試”代碼? (Writing "unit testable" code?)

按順序運行 TestNG 組並在每個組中並行測試 (Run TestNG groups sequentially and tests in each group in parallel)

需要從 VS2012 單元測試中識別我的 .csproj 文件 (Need to identify my .csproj file from VS2012 unit tests)

ANT 構建失敗並在 html 報告中給出 classNotFoundExceeption (ANT build fails and gives classNotFoundExceeption in html report)

測試有狀態的 Mojolicious 應用程序 (Testing stateful Mojolicious apps)

如何在 Rails 測試中斷言圖像源 (How to assert image source in rails test)

如果兩個塊中都出現錯誤,如何處理 Given/When/Then 語句和 AfterScenario 鉤子中的錯誤 (How to handle error in Given/When/Then statements and AfterScenario hook if error pops in both blocks)

如何發送帶有損壞 FCS 的以太網幀? (How do you send an Ethernet frame with a corrupt FCS?)

如何在嵌入式系統中執行回歸測試 (How to perform regression tests in embedded systems)

是否有 .NET 版本的 Concordion? (Is there a .NET version of Concordion?)

如何在 Ready API 中動態創建屬性? (How to create properties in Ready API dynamically?)

嘗試測試腳本 spec.ts 失敗,因為期望(如返回)在創建響應到來之前執行並在控制台中顯示未定義 (Trying Test Scripts spec.ts fails because expect(like return) executes before create response came and shows undefined in console)







留言討論