📜  Dart – 单元测试

📅  最后修改于: 2021-09-02 05:48:51             🧑  作者: Mango

单元测试是单独测试软件/应用程序的各个组件的过程,以确保每个组件都按预期运行。

它提供了多种优势,例如 –

  • 无需运行整个软件/应用程序即可测试单个组件的能力。
  • 轻松查明特定组件内部的错误。

Dart提供了一个名为test的包,它可以让开发人员很容易地进行单元测试。在本文中,我们将使用此包编写一些单元测试,演示各种用例和结果。

设置项目:

由于我们使用的是test,它是一个外部dart包,因此必须创建一个单独的项目来运行该项目。

我们必须创建一个pubspec.yaml文件,并将以下几行添加到项目中。

name: DartTesting

dev_dependencies:
  test:

然后我们必须运行以下命令

dart pub get

这将初始化一个名为DartTesting的项目,并将测试包安装为开发依赖项

接下来,我们可以创建一个main. dart文件将包含我们所有的代码并在那里导入测试包。

import 'package:test/test.dart';

编写示例函数:

首先,我们必须编写一个简单的函数来运行我们的测试。下面提供的是用于计算数组所有元素之和的代码。

Dart
// Get sum of all elements of an array
int getSumOfArray(List arr) {
  int res = 0;
  for (var i=0; i


Dart
main() {
    
  // Successful test for sum of array
  test('Get sum of array - success', () {
    int expectedValue = 15;
    int actualValue = getSumOfArray([1, 2, 3, 4, 5]);
    expect(expectedValue, actualValue);
  });
}


Dart
main() {
   
  // Unsuccessful test for sum of array
  test('Get sum of array - failure', () {
    int expectedValue = 40;
    int actualValue = getSumOfArray([1, 2, 3, 4, 5]);
    expect(expectedValue, actualValue);
  });
}


编写单元测试:

可以使用test()函数为上述函数编写单元测试。它需要 2 个参数

  1. 包含单元测试描述的字符串值
  2. 使用expect()函数的测试断言。必须为expect()函数提供 2 个值:
    • 预期值,由开发人员手动提供。
    • 实际值,通过运行相关函数
    • 如果这些值匹配,则单元测试成功,否则视为失败。

下面提供的是getSumOfArray()函数的单元测试代码。由于预期值和实际值匹配,这将是一次成功的测试。

Dart

main() {
    
  // Successful test for sum of array
  test('Get sum of array - success', () {
    int expectedValue = 15;
    int actualValue = getSumOfArray([1, 2, 3, 4, 5]);
    expect(expectedValue, actualValue);
  });
}

输出

00:00 +0: Get sum of array - success

00:00 +1: All tests passed!

Exited

处理失败的测试:

在这种情况下,预期值与实际值不同,因此测试将失败。

Dart

main() {
   
  // Unsuccessful test for sum of array
  test('Get sum of array - failure', () {
    int expectedValue = 40;
    int actualValue = getSumOfArray([1, 2, 3, 4, 5]);
    expect(expectedValue, actualValue);
  });
}

输出

00:00 +0: Get sum of array - failure

00:00 +0 -1: Get sum of array - failure [E]

  Expected: <15>
    Actual: <40>