乐闻世界logo
搜索文章和话题

How do you unittest exceptions in Dart?

1个答案

1

Unit testing exceptions is a common practice when performing unit tests in Dart. This ensures that your code correctly handles error scenarios. In Dart, the test package is commonly used for writing and running unit tests. To test exceptions, you can use the expect function in combination with throwsA to assert that a specific exception is thrown by an operation.

Below is a step-by-step guide and example on how to unit test exceptions in Dart:

1. Add Dependencies

First, ensure that your pubspec.yaml file includes the test dependency.

yaml
dev_dependencies: test: ^1.16.0

2. Write the Testable Function

Suppose we have a function that throws an exception when the input does not meet expectations. For example, a function that accepts an age and throws an exception if the age is less than 18:

dart
void checkAge(int age) { if (age < 18) { throw Exception('You must be at least 18 years old.'); } }

3. Write the Test Code

Next, write the code to test this function. We define test cases using the test method and use the expect function to assert that an exception is thrown.

dart
import 'package:test/test.dart'; void main() { group('checkAge', () { test('throws an exception if age is under 18', () { // Arrange & Act & Assert expect(() => checkAge(17), throwsA(isA<Exception>())); }); test('does not throw an exception if age is 18 or older', () { // Arrange & Act & Assert expect(() => checkAge(18), isNot(throwsA(isA<Exception>()))); }); }); }

4. Run the Test

Use the following command to run the test:

bash
dart test

Explanation

In the above test code:

  • Two test cases are defined using the test function.
  • We use expect to verify whether the tested function throws an exception under specific conditions.
    • throwsA(isA<Exception>()) checks if the tested function throws an exception of type Exception.
    • isNot(throwsA(...)) checks if the function does not throw an exception.

By doing this, you can ensure that your code correctly throws exceptions when encountering errors or unexpected inputs, making error handling more robust and predictable.

2024年7月20日 00:02 回复

你的答案