Testing And Benchmarking in Dart

Here’s the translation of the Go testing and benchmarking example to Dart, formatted in Markdown suitable for Hugo:

Unit testing is an important part of writing principled Dart programs. The test package provides the tools we need to write unit tests, and the dart test command runs tests.

For the sake of demonstration, this code is in the main.dart file, but it could be in any Dart file. Testing code typically lives in a separate file named test/[original_file_name]_test.dart.

import 'package:test/test.dart';

// We'll be testing this simple implementation of an integer minimum.
int intMin(int a, int b) {
  if (a < b) {
    return a;
  }
  return b;
}

void main() {
  // A test is created by using the `test` function from the `test` package.
  test('IntMin basic test', () {
    int ans = intMin(2, -2);
    // `expect` is used to assert the expected outcome.
    expect(ans, -2, reason: 'IntMin(2, -2) should return -2');
  });

  // Writing tests can be repetitive, so it's idiomatic to use a
  // group of tests, where test inputs and expected outputs are
  // listed in a list and a single loop walks over them and
  // performs the test logic.
  group('IntMin table driven tests', () {
    var tests = [
      {'a': 0, 'b': 1, 'want': 0},
      {'a': 1, 'b': 0, 'want': 0},
      {'a': 2, 'b': -2, 'want': -2},
      {'a': 0, 'b': -1, 'want': -1},
      {'a': -1, 'b': 0, 'want': -1},
    ];

    for (var tt in tests) {
      test('${tt['a']},${tt['b']}', () {
        int ans = intMin(tt['a'] as int, tt['b'] as int);
        expect(ans, tt['want']);
      });
    }
  });

  // Benchmark tests in Dart are typically done using the `benchmark` package.
  // Here's a simple example of how you might structure a benchmark:
  test('IntMin benchmark', () {
    for (int i = 0; i < 1000000; i++) {
      intMin(1, 2);
    }
  });
}

To run all tests in the current project in verbose mode:

$ dart test -r expanded

The output will look something like this:

00:00 +0: IntMin basic test
00:00 +1: IntMin table driven tests 0,1
00:00 +2: IntMin table driven tests 1,0
00:00 +3: IntMin table driven tests 2,-2
00:00 +4: IntMin table driven tests 0,-1
00:00 +5: IntMin table driven tests -1,0
00:00 +6: IntMin benchmark

All tests passed!

For more sophisticated benchmarking, you would typically use a dedicated benchmarking package like benchmark or benchmark_harness. These provide more detailed performance metrics and allow for more control over the benchmarking process.

Remember that Dart’s approach to testing and benchmarking is somewhat different from some other languages. It doesn’t have built-in benchmarking tools like Go does, but there are community packages that provide similar functionality.