When writing unit tests, you may find that the test code tends to become complicated when writing with various test cases.
For example, you can write tests in various cases, such as when testing a method that returns a certain value when logged in but returns null when not logged in, or when testing a method whose results change depending on the time of day, such as morning, noon, or night. There are many times when I want to.
TableDrivenTests, which is available in the Golang world, can help you with this .
TableDrivenTests is a method that allows you to declare test cases in a table format, and then run tests in a highly readable and comprehensive way by simply passing the test cases in order as test code parameters.
We will use a package called tuple published by google.dev .
As the name suggests, it allows you to define tuple data structures.
This time we are introducing TableDrivenTests, so the content of the test is appropriate. Suppose you want to write a test whose behavior changes depending on whether
you are logged in or not, which is true or false isAuthenticated int? sample()
tuple
Since we are using packages, Tuple
we can use types. Tuple
It seems to be compatible with this.
This time, Tuple2
we are using , to store item1
a bool indicating whether or not you are logged in, and the matcher we are expecting item2
void main() {
final testCases = [
Tuple2(true, 1),
Tuple2(false, null),
];
for (final testCase in testCases) {
test('authenticated is ${testCase.item1}', () {
expect(sample(testCase.item1), testCase.item2);
});
}
}
int? sample(bool isAuthenticated) {
return isAuthenticated ? 1 : null;
}
This time tuple
we implemented TableDrivenTests using the package, and this feature is being considered as a Dart language feature.
https://github.com/dart-lang/language/issues/68
In time, you may not need to rely on packages.