Computer ScienceChapter 3: Programming Fundamentals
3.5.1 Unit Test
A unit test
Explanation level
Introduction
In software development, unit testing is a crucial activity to ensure that every module of code functions properly, i.e., the code performs as desired. Unit tests are intended to test each line of code to make sure it functions properly. Error detection at an early stage is critical to prevent more serious issues in the later stages.
Definition
A unit test is a software testing method by which individual units of source code — such as functions, methods, or modules — are tested to determine whether they are fit for use.
Main Idea
Unit tests break the program into small pieces and test each piece separately. If every unit works correctly on its own, the whole program is more likely to work correctly when the units are combined.
Core Concept
Unit tests:
- Test individual parts of the code.
- Are usually written by developers.
- Are automated (run by a testing framework).
- Help detect errors early.
- Provide confidence when making changes.
Detailed Explanation
Why Unit Tests Are Important
Unit tests also help in outlining the function of every section of code. This makes it easier for developers to understand and maintain their code. If the unit tests continue to pass, you may be certain that the primary functionality will continue to function even after you make significant modifications or rearrange the code.
Key benefits:
- Early error detection: Catch bugs before they become bigger problems.
- Code quality: Ensures each part of the code works as expected.
- Documentation: Tests describe what the code is supposed to do.
- Confidence: Safe to refactor or modify code.
- Maintainability: Easier to understand and maintain code.
Scope of Unit Tests
Unit tests can be applied to:
- A function
- A module
- Even a single line of code
Example: Zakat Calculation
For instance, a mathematical formula is to be incorporated to calculate Zakat of yield from an agriculture land. So, the written formula needs to be tested by the developer for different values based on different possible scenarios, until this line of code passes multiple unit tests. Hence, unit tests ensure the quality of code, by providing developers the confidence in making changes, identify errors early, and facilitate code management.
Example: Unit Tests for `findItem` Function
Two test cases are presented for the code of the shopping list example. Test 1 looks for the object "milk," which we know exists and anticipates that the function will return "true." Test 2 looks for the nonexistent object "eggs" and anticipates a "false" response from the method. The tests' outcomes are displayed based on the return value of the `findItem` method.
```html <!DOCTYPE html> <html lang="en"> <head> <title>Unit Tests for Array Search</title> </head> <body> <h1>Unit Tests for 'findItem' Function</h1> <p id="testResults"></p>
<script> const shoppingList = ["apples", "bread", "milk", "cheese"];
function findItem(itemName) { for (let i = 0; i < shoppingList.length; i++) { if (shoppingList[i] === itemName) { return true; } } return false; }
let testResults = ""; testResults += "Test 1 (Existing Item): "; if (findItem("milk") === true) { testResults += "Passed\n"; } else { testResults += "Failed\n"; }
testResults += "\nTest 2 (Non-Existing Item): "; if (findItem("eggs") === false) { testResults += "Passed\n"; } else { testResults += "Failed\n"; }
document.getElementById("testResults").textContent = testResults; </script> </body> </html> ```
Output:
``` Unit Tests for 'findItem' Function
Test 1 (Existing Item): Passed Test 2 (Non-Existing Item): Passed ```
Explanation:
- The `findItem` function searches for an item in the `shoppingList` array.
- Test 1: Searches for "milk" (which exists) and expects `true`. The test passes.
- Test 2: Searches for "eggs" (which does not exist) and expects `false`. The test passes.
- The results are displayed on the webpage.
Structure of a Unit Test
A typical unit test has three parts:
- Arrange: Set up the data and conditions.
- Act: Call the function being tested.
- Assert: Check that the result matches the expected value.
Example:
```javascript // Arrange const shoppingList = ["apples", "bread", "milk", "cheese"];
// Act const result = findItem("milk");
// Assert if (result === true) { console.log("Test Passed"); } else { console.log("Test Failed"); } ```
Intermediate Level
At the intermediate level, you should understand how unit tests are written and run.
Writing a unit test:
- Identify the function to test.
- Decide on input values and expected outputs.
- Call the function with the input.
- Compare the actual output with the expected output.
- Report pass or fail.
Example:
```javascript function add(a, b) { return a + b; }
// Test 1 if (add(2, 3) === 5) { console.log("Test 1 Passed"); } else { console.log("Test 1 Failed"); }
// Test 2 if (add(0, 0) === 0) { console.log("Test 2 Passed"); } else { console.log("Test 2 Failed"); } ```
- Jest (JavaScript)
- Mocha (JavaScript)
- JUnit (Java)
- PyTest (Python)
These frameworks automate the process of running tests and reporting results.
Important Points
- - Unit testing tests individual units of code.
- - A unit can be a function, module, or line of code.
- - Unit tests help detect errors early.
- - Unit tests provide confidence when making changes.
- - Unit tests improve code quality and maintainability.
- - Tests have three parts: Arrange, Act, Assert.
- - Test frameworks automate unit testing.
- - Unit tests are part of Test-Driven Development (TDD).
Remember
- - Unit test = test one part.
- - Function, module, or line.
- - Early error detection.
- - Confidence in changes.
- - Arrange, Act, Assert.
- - Frameworks: Jest, Mocha, JUnit, PyTest.
- - TDD = test first, then code.
Common Mistakes
- - Testing too many things in one test.
- - Not testing edge cases (empty input, large input, negative numbers).
- - Making tests depend on each other.
- - Forgetting to run tests after changes.
- - Assuming that passing unit tests means the whole program is bug-free.
- - Writing tests after the code is complete (TDD says write tests first).
- - Not using a test framework (manual testing is error-prone).
- - Testing the wrong thing (testing implementation instead of behavior).
Quick Revision
- Unit testing tests individual units of code.
- A unit can be a function, module, or line.
- Unit tests help detect errors early.
- Unit tests provide confidence when making changes.
- Tests have three parts: Arrange, Act, Assert.
- Test frameworks automate unit testing.
- TDD: write test first, then code.
- Unit tests do not guarantee the program is bug-free.
60-Second Revision
- Unit test = test one part.
- Function, module, or line.
- Early error detection.
- Arrange, Act, Assert.
- Frameworks: Jest, Mocha, JUnit, PyTest.
- TDD = test first, then code.
- Warning: Passing unit tests does not mean the whole program is bug-free; integration and system testing are also needed.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.5.1 Unit Test
Sticky Notes · Quick Revision
Key Point 1
- Unit test = test one part.
Key Point 2
- Function, module, or line.
Key Point 3
- Early error detection.
Key Point 4
- Arrange, Act, Assert.
Key Point 5
- Frameworks: Jest, Mocha, JUnit, PyTest.
Key Point 6
- TDD = test first.
Key Point 7
- Confidence in changes.
Same supplied content as this Notes page (shared canonical source).