Skip to content

Latest commit

 

History

History
55 lines (44 loc) · 2.81 KB

2.1_Basics_of_Unit_Testing.md

File metadata and controls

55 lines (44 loc) · 2.81 KB

Basics of Unit Testing in Dart

Unit testing focuses on verifying the correctness of individual units of source code, such as functions or methods, in isolation from the rest of the application. In this section, we'll break down the fundamental concepts and practices of unit testing in Dart.

What is a "Unit"?

In the context of testing, a "unit" refers to the smallest testable part of any software. It can be an entire module or just a single function. The primary goal is to validate that each unit of the software code performs as expected.

Why Unit Testing?

  1. Quick Feedback: Unit tests are generally fast and can be run frequently, providing immediate feedback to developers.
  2. Improved Design: Writing tests often leads to better code design and modularity.
  3. Easier Refactoring: Tests ensure that refactoring doesn't introduce regressions.
  4. Documentation: Tests can serve as documentation, showcasing how a piece of code is expected to behave.

Writing a Unit Test in Dart

1. Choose the Unit to Test

Decide on a function or method that you want to test. For this example, let's consider a simple function that returns the sum of two numbers:

int sum(int a, int b) {
  return a + b;
}

2. Decide on Test Cases

Think about the different inputs this function can have and what the expected outputs are. For our sum function:

  • sum(3, 4) should return 7.
  • sum(-3, 4) should return 1.

3. Write the Test

import 'package:test/test.dart';
import 'path_to_your_function.dart';  // Adjust this import path

void main() {
  test('Positive numbers', () {
    expect(sum(3, 4), 7);
  });

  test('Mix of negative and positive numbers', () {
    expect(sum(-3, 4), 1);
  });
}

Run the tests using dart test in your terminal.

Mocking in Unit Tests

Often, you'll want to test units that have external dependencies like databases or APIs. In unit tests, these dependencies should be isolated using "mocks". Dart's mockito package is an excellent tool for this purpose, which we will delve into in a subsequent section.

Best Practices

  1. One Assertion per Test: Ideally, each test should verify just one behavior.
  2. Descriptive Test Names: Your test descriptions should explain what the test does, e.g., 'Calculating sum of two positive numbers'.
  3. Test Edge Cases: Apart from the usual cases, test boundary and unexpected input cases.
  4. Keep Tests Independent: One test should not depend on another. Each test should be standalone.

Conclusion

Unit tests form the backbone of any software testing strategy. They're vital for ensuring the correctness of individual units of code and building robust applications. In upcoming sections, we'll explore advanced unit testing techniques, patterns, and tools that are pivotal in Dart. Next