IntermediateTopic 49 of 104Software & Computing

Unit testing

Verifies small components in isolation.

In depth

Unit tests verify small units in isolation with assertions (pytest, JUnit). Good tests are fast, deterministic and independent; use mocks for external dependencies. Coverage metrics show tested lines but not test quality. The test pyramid favours many unit tests, fewer integration and UI tests.

Key points

  • Arrange-Act-Assert
  • Test doubles
  • Edge cases
Example

assert add(2,3)==5 is the simplest unit test.

Why it matters

Unit tests catch bugs early and make refactoring safe, which keeps code reliable as it changes.

Where this is used

  • Testing a function that converts units to check edge cases.
  • Verifying a parser handles empty input correctly.
  • Checking that a discount calculation returns the right value at the boundaries.

Frequently asked questions

What is Unit testing?

Verifies small components in isolation.

Why is it important to understand unit testing?

Unit tests catch bugs early and make refactoring safe, which keeps code reliable as it changes.

What makes a good unit test?

It tests one behaviour, is fast and independent, has a clear name and runs without network or external state.

What is a mock?

A stand-in object that replaces a real dependency in a test, so the unit can be tested in isolation.

How is Unit testing used in practice?

Typical applications include testing a function that converts units to check edge cases, verifying a parser handles empty input correctly and checking that a discount calculation returns the right value at the boundaries.

What should I learn before Unit testing?

Study "UML and modelling" first (topic 48 of 104 in Software & Computing). It covers the groundwork this topic builds on.

What are the key points of Unit testing?

Arrange-Act-Assert. Test doubles. Edge cases.

Can you give an example of Unit testing?

assert add(2,3)==5 is the simplest unit test.

What comes after Unit testing?

The next topic is "Test-driven development", which builds directly on this one.

How difficult is Unit testing?

It is classed as Intermediate in Software & Computing (topic 49 of 104). It is an intermediate topic. Work through the beginner topics in Software & Computing first.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.

Related topics