Web制作、Web開発の歩き方

分かりやすいコードの書き方

第7話:テストがしやすいコード

(最終更新日:2025.4.23)


分かりやすいコード

この記事は5分で読めます!
(絵が小さい場合はスマホを横に)

テストしやすいコードに!

コードが分かりにくい、読みにくい、変更しづらい。 そんな悩みを解決するための一つの基準が「テストしやすいコードかどうか」である。 テストがしやすいコードとは、外部に依存せず、単独で動作確認ができるコードだ。 これはそのまま「読みやすく、再利用しやすく、壊れにくいコード」にもつながる。 今回は「テストしやすさ」から見た分かりやすいコードの条件について解説する。



1.テストしやすいコードは分かりやすいコード

なぜ「テストしやすいコードは分かりやすいコードなのか」。 これは、テストしやすいコードは下記の4つの特徴を持っているからである。 つまり「テストしやすい=構造が明快で、責任が分かれている」ということだ。 これはそのまま、可読性・保守性・拡張性の高さに直結する。

  • 目的が明確 :テストの対象がはっきりしている
  • 副作用が少ない:テスト中に外部の影響を受けにくい
  • 単独で動く:外部環境や状態に依存しない
  • 関数が小さい: テスト範囲を限定しやすい

このことを踏まえて、次のテストしやすいコードを書くポイントを見ていこう。

2.テストしやすいコードを書くポイント

テストをしやすいコードには3つのポイントがある。 「依存性を減らす」「モックやダミーを使う」「ユニットテストが書きやすい関数設計」である。 それぞれ順番に見ていこう。

2.1 依存性を減らす(ロジックを分離する)
まずは「依存性を減らす」だ。 下記は「依存性を減らす」ための悪い例と良い例になる。 悪い例ではデータベースに接続してしまうので単体テストが難しい。

悪い例

次に良い例だ。データ取得処理を外から注入できる。この方法だと、テストはモック関数を渡せる。 単体でテストがしやすくなる。

良い例

2.2 モックやダミーを使う
外部のAPIやDBに依存している関数は、テスト時に仮の関数(モック)を差し替えることで検証可能になる。 下記はモック関数の例になる。これにより、本物のデータベースを使わなくても、安全、簡単にテストができる。 user_idが123の時のユーザー名を返す。

モック関数を使った例

2.3 ユニットテストが書きやすい関数の設計
関数の責任が1つだけで、入力から出力の意図が明確なら、テストは簡単だ。 下記は、その例になる。単純に価格に税率をかけて税込の値段にしている。 そして、関数自体が状態を持っていないので、テストがしやすい。

テストがしやすいコードの例

3.テストがしにくいコードとしやすいコードの比較

最後に、テストがしにくいコードとしやすいコードの比較を挙げる。 次のようにまとめられる。外部依存が少なく、責任の範囲が1つで、副作用を持たない。 再現性が高く、テストコードが書きやすいというものだ。

テストしやすい、しにくいコードの比較

項目 テストしにくいコード テストしやすいコード
外部依存 直接DBやAPIを呼び出す 処理を外から注入できる
関数の責任 複数の処理が混在 単一の責務に絞っている
副作用 グローバル変数を変更 副作用を持たない
再現性 環境に依存して結果が変わる 常に同じ入力で同じ結果が出る
テストコード 書くのが難しい 簡単に書けてすぐ実行できる

4.まとめ

今回、テストがしやすいコードは、設計がシンプルで読みやすいことが分かった。 加えて、外部依存を避けてそれ単体で意味が成立する、テストできるようにすることが重要だ。 そのためには、モックやダミーを使うことが必要だということも分かった。 今回のようなコードを書くことを心がけることで、可読性・保守性・信頼性のすべてが上がるはずだ。

▼参考図書、サイト

 「リーダブルコード」 Dustin Boswell、Trevor Foucher 著、角 征典 訳 オライリー

How to Write Understandable Code Episode 7: Code That’s Easy to Test (Last updated: April 23, 2025) Understandable Code You can read this article in 5 minutes! (If the image is too small, try rotating your phone) Make your code testable! Is your code hard to read, understand, or modify? One useful standard to solve these issues is whether the code is easy to test. Code that is easy to test is self-contained, doesn't rely on external systems, and can be verified independently. This naturally leads to code that is readable, reusable, and robust. In this article, we’ll explore what makes code understandable from the perspective of testability. [Table of Contents] Testable Code Is Understandable Code Tips for Writing Testable Code Comparison: Hard-to-Test vs Easy-to-Test Code Summary 1. Testable Code Is Understandable Code Why is testable code also understandable? Because such code typically has four traits: Clear purpose: The test target is obvious Few side effects: Little to no external influence during testing Self-contained: Not dependent on external states or systems Small functions: Easier to isolate and test These traits contribute directly to better readability, maintainability, and scalability. Now, let’s look at some practical tips for writing testable code. 2. Tips for Writing Testable Code There are three key points: “Reduce dependencies,” “Use mocks and dummies,” and “Design functions that are easy to test.” Let’s go through each one. 2.1 Reduce Dependencies (Separate Logic) First, reduce dependencies. Below are examples of bad and good practices. The bad example connects directly to the database, making unit testing difficult. Bad Example In contrast, the good example allows data retrieval to be injected from outside, enabling the use of mock functions for testing. Good Example 2.2 Use Mocks and Dummies If a function relies on an external API or database, you can test it by substituting it with a mock function. Here's an example. This mock function returns a username for user_id 123, allowing safe testing without real databases. Using a Mock Function 2.3 Design Functions for Unit Testing A function with a single responsibility and a clear relationship between input and output is easy to test. Here's an example: the function calculates tax-inclusive prices and doesn’t maintain any internal state, making it easy to verify. Example of Testable Code 3. Comparison: Hard-to-Test vs Easy-to-Test Code Lastly, here's a comparison. Code with fewer external dependencies, clear responsibilities, and no side effects is more reproducible and easier to write tests for. Comparison: Hard-to-Test vs Easy-to-Test Code Aspect Hard-to-Test Code Easy-to-Test Code External Dependencies Directly accesses DB or APIs Allows injection from outside Function Responsibility Handles multiple concerns Single responsibility Side Effects Changes global state No side effects Reproducibility Depends on the environment Always returns the same output for the same input Test Code Hard to write Easy to write and run 4. Summary We’ve learned that testable code is often simple and easy to read. Avoiding external dependencies and ensuring each unit can be tested on its own is key. Using mocks and dummies helps achieve this. Writing such code will improve readability, maintainability, and reliability. ▼References  “The Art of Readable Code” by Dustin Boswell and Trevor Foucher, translated by Masanori Kado, O'Reilly Japan