跳到主要内容
英国伦敦 · 创立于 1994 年
中文

Unit 4: Testing and Quality Assurance

Why and how software is tested, practical techniques for designing good tests, and the wider practices, including secure coding, that build quality into software from the start.

Unit 4 of 5 · about 54 minutes

4.1 Why we test and the levels of testing

Testing is the process of checking that software behaves as intended and finding defects before users do. It is one of the most important activities in software engineering, because defects found late, especially after release, are usually far more expensive and disruptive to fix than those found early. Testing also gives teams the confidence to change software quickly, knowing that mistakes will be caught.

What testing can and cannot do

Testing can show the presence of defects, but it cannot prove their absence. Even a simple program can have more possible combinations of inputs than could ever be tested. Testing is therefore about managing risk: focusing effort where defects are most likely or would cause most harm, and using techniques that find many defects with a reasonable number of tests.

Verification and validation

Two related ideas are worth distinguishing. Verification asks "are we building the product right?", meaning does the software meet its specification. Validation asks "are we building the right product?", meaning does it actually meet users' needs. Software can pass every verification test and still fail validation if the requirements themselves were wrong.

Levels of testing

  • Unit testing checks the smallest testable parts of the code, such as individual functions, in isolation. Unit tests are usually written by developers, run in seconds and are executed many times a day.
  • Integration testing checks that different parts of the system work correctly together, such as the application and its database, or two services communicating through an API.
  • System testing checks the complete, integrated system against its requirements, including end-to-end scenarios such as a customer placing and paying for an order.
  • Acceptance testing confirms that the system meets business needs and is ready for use. It often involves users or the product owner, and may be based on the acceptance criteria written for each user story.

The test pyramid

A widely used model, the test pyramid, suggests how to balance these levels. At the base are many fast, inexpensive unit tests. In the middle are fewer integration tests. At the top are a small number of slow, broader end-to-end tests. This balance gives quick feedback and broad coverage while keeping the test suite fast and reliable. Teams that rely mainly on slow end-to-end tests, an "inverted pyramid", often find their tests take hours to run and fail unpredictably.

Functional and non-functional testing

Most tests check functionality, but non-functional qualities also need testing:

  • Performance and load testing: how the system behaves under expected and peak usage.
  • Security testing: whether the system resists attacks and protects data.
  • Usability testing: whether real users can complete tasks easily.
  • Accessibility testing: whether people with disabilities can use the system, for example with screen readers or keyboard-only navigation, often checked against the international Web Content Accessibility Guidelines.
  • Compatibility testing: whether the system works across different browsers and devices.

Automated and manual testing

Automated tests are written as code and can run quickly and repeatedly, making them ideal for checking that existing behaviour still works after changes. This is known as regression testing. Manual testing remains valuable for exploring new features, judging usability and finding unexpected problems. Exploratory testing, in which a skilled tester investigates the software creatively without a fixed script, often uncovers defects that scripted tests miss.

Remember: quality is the whole team's responsibility. Testers bring valuable skills, but developers, product owners and designers all contribute to preventing and finding defects.

Test environments and data

Tests need suitable environments that resemble the live system closely enough to be meaningful. Test data should cover realistic and unusual cases. Using copies of real personal data for testing raises privacy and security concerns; many organisations instead use synthetic or properly anonymised data.

Common mistakes

  • Leaving testing until the end of a project, when there is little time to fix what is found.
  • Relying only on slow end-to-end tests.
  • Testing only the "happy path" where everything goes right.
  • Ignoring non-functional qualities such as performance and accessibility.
  • Using real customer data in test environments without proper safeguards.

In practice

Ask a development team you work with how their testing is organised. What proportion of tests are automated? How long does the full test suite take to run? How are performance, security and accessibility checked? If you are a user or stakeholder, take part in acceptance testing when invited: your knowledge of real tasks often reveals problems that technical tests cannot.

4.2 Designing good tests

Writing tests is easy; writing tests that find defects efficiently is a skill. Good test design focuses effort on the inputs and situations most likely to reveal problems, avoids redundant tests and produces tests that are clear and reliable. This lesson introduces core techniques that apply whether tests are automated or manual.

Equivalence partitioning

Many inputs can be grouped into equivalence partitions: sets of values that the software should treat in the same way. If one value in a partition works, others in the same partition probably will too, so you only need to test one representative from each.

Consider a system that offers free delivery for orders of 50 or more, charges standard delivery for orders from 0.01 to 49.99, and rejects orders of zero or less. There are three partitions: invalid (zero or below), standard delivery and free delivery. Testing one value from each, such as -5, 20 and 80, covers the main behaviours with just three tests.

Boundary value analysis

Defects cluster at the edges of partitions, where a programmer might write "greater than" instead of "greater than or equal to". Boundary value analysis tests values at and just either side of each boundary. In the delivery example, useful tests include 0, 0.01, 49.99 and 50. These few tests are likely to reveal a mistake in how the boundaries were coded.

Decision tables

When behaviour depends on combinations of conditions, a decision table lists each combination and the expected outcome. For example, a discount might depend on whether a customer is a member and whether a promotion code is used. Listing all four combinations makes it clear what should happen in each case and ensures none is forgotten.

Testing errors and edge cases

Good test sets go beyond normal use. Consider:

  • empty inputs, very long inputs and unexpected characters;
  • missing or invalid data from other systems;
  • actions performed in an unexpected order, or twice;
  • failure of a dependency, such as a payment service being unavailable;
  • dates around month ends, leap years and changes to and from daylight saving time;
  • multiple users changing the same record at the same time.

Characteristics of good automated tests

  • Fast, so they can be run frequently.
  • Independent, so each test can run alone and in any order.
  • Repeatable, giving the same result every time. Tests that pass and fail unpredictably, often called flaky tests, erode trust and should be fixed or removed.
  • Clear, with a descriptive name stating what is being tested and the expected result.
  • Focused, checking one behaviour so that a failure points directly to the problem.

A common structure for each test is Arrange, Act, Assert: set up the necessary conditions, perform the action being tested and check the result.

Tip: whenever a defect is found, write a test that reproduces it before fixing it. The test confirms the fix works and protects against the same defect returning in future.

Test-driven development

Test-driven development (TDD) reverses the usual order of coding and testing. The developer works in short cycles, often summarised as "red, green, refactor":

  1. Red: write a small test for a behaviour that does not yet exist, and see it fail.
  2. Green: write the simplest code that makes the test pass.
  3. Refactor: improve the design of the code while keeping all tests passing.

TDD encourages simple, testable designs and produces a comprehensive set of tests as a by-product. Related approaches, such as behaviour-driven development, express tests in a structured, readable form close to acceptance criteria, such as Given, When, Then, so that business stakeholders can understand and contribute to them.

Code coverage

Code coverage measures the proportion of code executed by tests. Low coverage indicates untested areas, which is useful information. High coverage, however, does not prove that tests are good: tests can run code without checking its results properly. Treat coverage as a guide to gaps, not as a target in itself.

Common mistakes

  • Writing many tests for normal cases and none for boundaries or errors.
  • Tolerating flaky tests until nobody trusts the test suite.
  • Writing tests that check implementation details rather than behaviour, so they break whenever code is restructured.
  • Pursuing a coverage percentage at the expense of meaningful tests.

In practice

Choose a simple rule from your work, such as an eligibility threshold, a discount or a deadline. Identify its equivalence partitions and boundaries, and list the test values you would use. Add three edge cases and describe the expected result for each. Sharing this list with a development team is a practical way to contribute to quality, even if you never write test code yourself.

4.3 Building quality in: reviews, static analysis and secure coding

Testing finds defects after code has been written. It is even better to prevent defects from being introduced at all. Mature software teams combine testing with practices that build quality in throughout development. This approach is sometimes described as "shifting left": moving quality and security activities earlier in the life cycle, where problems are cheaper to fix.

Quality assurance and quality control

Quality control focuses on finding defects in the product, for example through testing. Quality assurance is broader: it concerns the processes and practices that prevent defects, such as clear requirements, design reviews, coding standards, code review and continuous improvement. Both are needed.

Static analysis

Static analysis tools examine source code without running it. They can detect:

  • likely bugs, such as variables used before they are set or values that can never be reached;
  • violations of coding standards and inconsistent formatting;
  • overly complex functions that are hard to understand and test;
  • certain security vulnerabilities, such as unsafe handling of user input;
  • known vulnerable versions of third-party libraries.

Running these tools automatically on every change gives fast, consistent feedback and frees human reviewers to focus on design and logic. Tools need tuning, however; too many unimportant warnings cause people to ignore them all.

Secure coding

Many security breaches exploit flaws in application code. Secure coding means writing software that resists attack from the start. The OWASP Top 10, a regularly updated awareness document from the Open Worldwide Application Security Project, lists the most critical categories of web application security risk. Recurring themes include:

  • Broken access control: users able to view or change data they should not, for example by altering an account number in a web address.
  • Injection: untrusted input being interpreted as commands, as in SQL injection, where a malicious value entered into a form manipulates a database query.
  • Cryptographic failures: sensitive data not encrypted properly, or weak algorithms used.
  • Security misconfiguration: default settings, unnecessary features enabled or detailed error messages revealing internal information.
  • Vulnerable and outdated components: using third-party libraries with known flaws.
  • Authentication failures: weak password handling or session management.

Core secure coding practices

  1. Validate all input from users and other systems, accepting only what is expected.
  2. Use parameterised queries rather than building database commands from text, which prevents SQL injection.
  3. Encode output appropriately so that data cannot be interpreted as executable code in a web page.
  4. Check authorisation on the server for every request, never relying on the user interface to hide options.
  5. Use well-established security libraries for encryption and authentication instead of writing your own.
  6. Keep secrets out of code, storing them in dedicated secret management tools.
  7. Keep dependencies updated and monitor them for newly published vulnerabilities.
  8. Handle errors safely, logging details internally while showing users only general messages.

Remember: never trust input. Anything that comes from outside your code, whether a form, a file, a web address or another system, may be malicious or malformed and must be checked.

Software supply chain

Modern applications depend heavily on open-source and third-party components, which may in turn depend on others. A flaw in one widely used library can affect many thousands of applications. Teams manage this risk by keeping an inventory of components, sometimes called a software bill of materials, using automated tools to flag known vulnerabilities, choosing well-maintained libraries and applying updates promptly.

Threat modelling

Threat modelling is a structured way of thinking about how a system could be attacked, ideally during design. A simple version asks four questions: what are we building, what can go wrong, what are we going to do about it, and did we do a good enough job? Even an hour of structured discussion can reveal significant risks early.

Measuring quality

Useful indicators include the number of defects found after release, how quickly defects are fixed, the reliability of automated tests and trends in static analysis findings. As with all metrics, these should inform improvement rather than be used to blame individuals.

In practice

Ask a development team which static analysis and dependency scanning tools they use, and whether they run automatically on every change. Ask whether threat modelling takes place for new features. If you are involved in specifying a feature that handles personal data or payments, raise security requirements, such as access rules and input validation, at the start rather than leaving them until testing.

Case study: Catching a boundary defect at a ticketing company

Eventora, a fictional online ticketing company, offered a reduced price for children aged under 16. After a release, customer service received complaints from parents of children aged exactly 16, who were being offered the child price, and from parents of 15-year-olds whose discount had disappeared on their birthday.

Investigation found that age was calculated from the date of birth using a simplified formula that was sometimes wrong by a day around birthdays, and that the comparison used "16 or under" rather than "under 16". Existing tests used only ages such as 8 and 30, so neither boundary had been checked.

The team wrote tests for ages 15, 16 and 17, and for dates on and either side of a sixteenth birthday, including leap-year birthdays. All failed as expected. The developer replaced the formula with the platform's standard date library and corrected the comparison. The team added boundary value analysis to its definition of done for any rule involving thresholds, and introduced a static analysis rule flagging hand-written date calculations.

Activity

Choose a business rule involving a threshold, such as eligibility for a discount, a late payment fee or a booking cut-off time. Identify the equivalence partitions and boundary values, and write at least six test cases with inputs and expected results. Add one security-related test that checks the system handles invalid or malicious input safely.

Compare with a model answer

A good answer states the rule precisely, for example: "A late fee of 10 is charged if payment is received more than 14 days after the due date." It identifies partitions: on time (0 to 14 days late), late (15 days or more) and invalid (payment date before the invoice date or missing).

Test cases include boundaries and representatives: 0 days late, 14 days late (no fee), 15 days late (fee), 60 days late (fee), a missing payment date (error message) and a date before the invoice (error). Each has a clear expected result. The security test might enter text containing database commands into the payment reference field and expect it to be stored as plain text, with no effect on the database and no detailed error shown to the user.

Key takeaways

  • Testing manages risk by finding defects early; it can show their presence but cannot prove their absence.
  • Unit, integration, system and acceptance tests check different things, and the test pyramid favours many fast unit tests over slow end-to-end tests.
  • Equivalence partitioning, boundary value analysis and decision tables help design efficient tests, including for errors and edge cases.
  • Good automated tests are fast, independent, repeatable and clear, and every defect fixed should gain a test that reproduces it.
  • Static analysis, secure coding practices, dependency management and threat modelling build quality and security in from the start.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 3 Unit 5 →
WhatsApp