### Use setUp() and tearDown() for Test Fixtures in Dart Source: https://pub.dev/documentation/test/latest/index.html Implement setup and teardown logic for tests using `setUp()` and `tearDown()`. `setUp()` runs before each test, and `tearDown()` runs after, even if a test fails, ensuring cleanup. ```dart import 'package:test/test.dart'; import 'dart:io'; void main() { late HttpServer server; late Uri url; setUp(() async { server = await HttpServer.bind('localhost', 0); url = Uri.parse('http://${server.address.host}:${server.port}'); }); tearDown(() async { await server.close(force: true); server = null; url = null; }); // ... } ``` -------------------------------- ### Test Setup and Teardown Functions Source: https://pub.dev/documentation/test/latest/scaffolding Functions for registering callbacks to run before, after, or once before/after all tests. ```APIDOC ## setUp ### Description Registers a function to be run before tests. ### Method `setUp(FutureOr callback())` ### Parameters - **callback** (FutureOr) - The function to run before tests. ## setUpAll ### Description Registers a function to be run once before all tests. ### Method `setUpAll(FutureOr callback(), {TestLocation? location})` ### Parameters - **callback** (FutureOr) - The function to run once before all tests. - **location** (TestLocation, optional) - The location of the setup. ## tearDown ### Description Registers a function to be run after tests. ### Method `tearDown(FutureOr callback())` ### Parameters - **callback** (FutureOr) - The function to run after tests. ## tearDownAll ### Description Registers a function to be run once after all tests. ### Method `tearDownAll(FutureOr callback(), {TestLocation? location})` ### Parameters - **callback** (FutureOr) - The function to run once after all tests. - **location** (TestLocation, optional) - The location of the teardown. ## addTearDown ### Description Registers a function to be run after the current test. ### Method `addTearDown(FutureOr callback())` ### Parameters - **callback** (FutureOr) - The function to run after the current test. ``` -------------------------------- ### Match examples for equalsIgnoringWhitespace Source: https://pub.dev/documentation/test/latest/test/equalsIgnoringWhitespace.html These examples demonstrate successful matches when using equalsIgnoringWhitespace. The matcher handles variations in spacing, including multiple spaces between words and leading/trailing spaces. ```dart expect("hello world", equalsIgnoringWhitespace("hello world")); ``` ```dart expect(" hello world", equalsIgnoringWhitespace("hello world")); ``` ```dart expect("hello world ", equalsIgnoringWhitespace("hello world")); ``` -------------------------------- ### Platform-Specific Configuration Example Source: https://pub.dev/documentation/test/latest/test/group.html Demonstrates how to configure tests within a group on a platform-by-platform basis using the `onPlatform` parameter. ```dart group('potentially slow tests', () { // ... }, onPlatform: { // These tests are especially slow on Windows. 'windows': Timeout.factor(2), 'browser': [ Skip('TODO: add browser support'), // They'll be slow on browsers once it works on them. Timeout.factor(2) ] }); ``` -------------------------------- ### Dart Test onPlatform Example Source: https://pub.dev/documentation/test/latest/test/test.html Example demonstrating the use of the `onPlatform` parameter to configure tests differently for various platforms, such as setting timeouts or skipping tests. ```dart test('potentially slow test', () { // ... }, onPlatform: { // This test is especially slow on Windows. 'windows': Timeout.factor(2), 'browser': [ Skip('TODO: add browser support'), // This will be slow on browsers once it works on them. Timeout.factor(2) ] }); ``` -------------------------------- ### Initialize Matcher Source: https://pub.dev/documentation/test/latest/test/Matcher/Matcher.html Use this constructor to create a new instance of Matcher. No specific setup or imports are required beyond the Matcher definition. ```javascript const Matcher(); ``` -------------------------------- ### setUp Function Source: https://pub.dev/documentation/test/latest/test/setUp.html Registers a function to be run before tests. This function will be called before each test is run. The callback may be asynchronous; if so, it must return a Future. If called within a test group, it applies only to tests in that group. Callbacks will be run after any set-up callbacks in parent groups or at the top level, and in the order they were declared. ```APIDOC ## setUp Function ### Description Registers a function to be run before tests. This function will be called before each test is run. The callback may be asynchronous; if so, it must return a Future. If called within a test group, it applies only to tests in that group. Callbacks will be run after any set-up callbacks in parent groups or at the top level, and in the order they were declared. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Implementation ```dart void setUp(FutureOr Function() callback) => _declarer.setUp(callback); ``` ### Response #### Success Response (200) This function does not return a value directly. Its effect is to register a callback for test execution. #### Response Example N/A ``` -------------------------------- ### Example Usage of CustomMatcher Source: https://pub.dev/documentation/test/latest/test/CustomMatcher-class.html Demonstrates how to use the CustomMatcher class to create a custom assertion. ```APIDOC ### Example ```dart class HasPrice extends CustomMatcher { HasPrice(matcher) : super("Widget with price that is", "price", matcher); featureValueOf(actual) => (actual as Widget).price; } // Usage: expect(inventoryItem, HasPrice(greaterThan(0))); ``` ``` -------------------------------- ### Hybrid Test: WebSocket Server Setup Source: https://pub.dev/documentation/test/latest/index.html Sets up a WebSocket server on the VM isolate. This code is loaded by `spawnHybridUri` and communicates the server's port back to the browser test. ```dart // ## test/web_socket_server.dart // The library loaded by spawnHybridUri() can import any packages that your // package depends on, including those that only work on the VM. import 'package:shelf/shelf_io.dart' as io; import 'package:shelf_web_socket/shelf_web_socket.dart'; import 'package:stream_channel/stream_channel.dart'; // Once the hybrid isolate starts, it will call the special function // hybridMain() with a StreamChannel that's connected to the channel // returned spawnHybridCode(). hybridMain(StreamChannel channel) async { // Start a WebSocket server that just sends "hello!" to its clients. var server = await io.serve(webSocketHandler((webSocket, _) { webSocket.sink.add('hello!'); }), 'localhost', 0); // Send the port number of the WebSocket server to the browser test, so // it knows what to connect to. channel.sink.add(server.port); } ``` -------------------------------- ### Example Platform Selector Usage Source: https://pub.dev/documentation/test/latest/index.html Use platform selectors with the `@TestOn` annotation to specify the environments where a test should run. This example targets browsers excluding Chrome, compiled with dart2js. ```dart @TestOn('browser && !chrome && dart2js') ``` -------------------------------- ### Register Pre-Test Setup Callback Source: https://pub.dev/documentation/test/latest/test/setUp.html Use this function to register a callback that runs before each test. The callback can be asynchronous and must return a Future if so. It applies to tests within its scope and runs after parent group callbacks. ```dart void setUp(FutureOr Function() callback) => _declarer.setUp(callback); ``` -------------------------------- ### Register Callback Before All Tests Source: https://pub.dev/documentation/test/latest/test/setUpAll.html Use this function to register a callback that runs once before all tests. The callback can be asynchronous and must return a Future if so. Prefer setUp for most cases; use setUpAll only if the callback is prohibitively slow. ```dart void setUpAll( FutureOr Function() callback, {TestLocation? location} ) => _declarer.setUpAll(callback, location: location); ``` -------------------------------- ### startsWith Function Implementation Source: https://pub.dev/documentation/test/latest/test/startsWith.html This function returns a matcher that checks if the input string starts with the provided prefixString. It's a factory for creating specific string-matching logic. ```dart Matcher startsWith(String prefixString) => _StringStartsWith(prefixString); ``` -------------------------------- ### Example of noSuchMethod Invocation Source: https://pub.dev/documentation/test/latest/fake/Fake/noSuchMethod.html This example demonstrates how a dynamic member invocation on an integer triggers the noSuchMethod method, resulting in a runtime error. ```dart dynamic object = 1; object.add(42); // Statically allowed, run-time error ``` -------------------------------- ### addAll Method Source: https://pub.dev/documentation/test/latest/test/StringDescription/addAll.html Appends an Iterable `list` of objects to the description, using the specified `separator` and framing the list with `start` and `end`. ```APIDOC ## addAll Method ### Description Appends an Iterable `list` of objects to the description, using the specified `separator` and framing the list with `start` and `end`. ### Method N/A (This is a method within a class, not a standalone API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) N/A #### Response Example None ``` -------------------------------- ### Non-match examples for equalsIgnoringWhitespace Source: https://pub.dev/documentation/test/latest/test/equalsIgnoringWhitespace.html These examples illustrate cases where equalsIgnoringWhitespace will not match. The matcher requires strings to be equivalent after whitespace normalization; completely removing spaces or inserting spaces within words will result in a non-match. ```dart expect("helloworld", equalsIgnoringWhitespace("hello world")); ``` ```dart expect("he llo world", equalsIgnoringWhitespace("hello world")); ``` -------------------------------- ### TestOn Constructor Implementation Source: https://pub.dev/documentation/test/latest/test/TestOn/TestOn.html Use this constructor to create a TestOn object, providing the expression string during initialization. No additional setup is required. ```dart const TestOn(this.expression); ``` -------------------------------- ### Bootstrap VM Test with Isolate Communication Source: https://pub.dev/documentation/test/latest/bootstrap_vm/internalBootstrapVmTest.html Use this function to set up a VM test that communicates with the test runner over an isolate. It requires a function to get the main test suite and a SendPort for communication. ```dart void internalBootstrapVmTest(Function() getMain, SendPort sendPort) { var platformChannel = MultiChannel(IsolateChannel.connectSend(sendPort)); var testControlChannel = platformChannel.virtualChannel()..pipe(serializeSuite(getMain)); platformChannel.sink.add(testControlChannel.id); platformChannel.stream.forEach((message) { assert(message == 'debug'); debugger(message: 'Paused by test runner'); platformChannel.sink.add('done'); }); } ``` -------------------------------- ### Implement addAll Method Source: https://pub.dev/documentation/test/latest/test/StringDescription/addAll.html Appends an Iterable `list` of objects to the description, using the specified `separator` and framing the list with `start` and `end`. This method is part of the Description class. ```dart @override Description addAll( String start, String separator, String end, Iterable list, ) { var separate = false; add(start); for (var item in list) { if (separate) { add(separator); } addDescriptionOf(item); separate = true; } add(end); return this; } ``` -------------------------------- ### setUpAll Function Source: https://pub.dev/documentation/test/latest/test/setUpAll.html Registers a function to be run once before all tests. The callback can be asynchronous and must return a Future if so. It runs before all tests in the current group and after any setUpAll callbacks in parent groups. It will not run if no tests in the group are executed. ```APIDOC ## setUpAll Function ### Description Registers a function to be run once before all tests. `callback` may be asynchronous; if so, it must return a Future. If this is called within a test group, `callback` will run before all tests in that group. It will be run after any setUpAll callbacks in parent groups or at the top level. It won't be run if none of the tests in the group are run. **Note**: This function makes it very easy to accidentally introduce hidden dependencies between tests that should be isolated. In general, you should prefer setUp, and only use setUpAll if the callback is prohibitively slow. ### Method N/A (This is a function definition, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## Implementation ```dart void setUpAll( FutureOr Function() callback, { TestLocation? location, }) => _declarer.setUpAll(callback, location: location); ``` ``` -------------------------------- ### Using TypeMatcher.having to validate RangeError features Source: https://pub.dev/documentation/test/latest/test/TypeMatcher/having.html This example demonstrates how to use the `having` method to create a TypeMatcher that validates a RangeError's message and its start and end properties. ```dart /// Validates that the object is a [RangeError] with a message containing /// the string 'details' and `start` and `end` properties that are `null`. final _rangeMatcher = isRangeError .having((e) => e.message, 'message', contains('details')) .having((e) => e.start, 'start', isNull) .having((e) => e.end, 'end', isNull); ``` -------------------------------- ### Validate Type and Attributes with TypeMatcher.having Source: https://pub.dev/documentation/test/latest/test/TypeMatcher-class.html Chain multiple calls to `having` to verify multiple aspects of an object after validating its type. This example validates a RangeError's start and end attributes. ```dart void shouldThrowRangeError(int value) { throw RangeError.range(value, 10, 20); } expect( () => shouldThrowRangeError(5), throwsA(const TypeMatcher() .having((e) => e.start, 'start', greaterThanOrEqualTo(10)) .having((e) => e.end, 'end', lessThanOrEqualTo(20)))); ``` -------------------------------- ### Get Length Property Implementation Source: https://pub.dev/documentation/test/latest/test/Description/length.html This snippet shows the basic implementation of the 'get length' property in C++. ```cpp int get length; ``` -------------------------------- ### Initialize StringDescription with Initial Content Source: https://pub.dev/documentation/test/latest/test/StringDescription/StringDescription.html Use this constructor to create a StringDescription and set its initial content. The `init` parameter accepts a string. ```dart StringDescription([String init = '']) { _out.write(init); } ``` -------------------------------- ### Define isRangeError Constant Source: https://pub.dev/documentation/test/latest/test/isRangeError-constant.html Use this constant to create a TypeMatcher for RangeError. No additional setup is required. ```dart const isRangeError = TypeMatcher(); ``` -------------------------------- ### StringDescription Constructor Source: https://pub.dev/documentation/test/latest/test/StringDescription/StringDescription.html Initializes the StringDescription with optional initial contents. ```APIDOC ## StringDescription Constructor ### Description Initializes the description with initial contents `init`. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart StringDescription(['initial content']) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Define isArgumentError Matcher Source: https://pub.dev/documentation/test/latest/test/isArgumentError-constant.html Use this constant to create a matcher for ArgumentError. It requires no additional setup. ```dart const isArgumentError = TypeMatcher(); ``` -------------------------------- ### Description Class Overview Source: https://pub.dev/documentation/test/latest/test/Description-class.html This section details the constructors, properties, and methods available for the Description class. ```APIDOC ## Description Class ### Description Matchers build up their error messages by appending to Description objects. This interface is implemented by StringDescription. ### Constructors #### Description() Creates a new Description object. ### Properties - **hashCode** (int) - The hash code for this object. - **length** (int) - The length of the description. - **runtimeType** (Type) - A representation of the runtime type of the object. ### Methods #### add(String text) → Description Adds arbitrary text to the description. #### addAll(String start, String separator, String end, Iterable list) → Description Adds a description of an Iterable `list`, with appropriate `start` and `end` markers and inter-element `separator`. #### addDescriptionOf(Object? value) → Description Adds a meaningful description of a value. #### noSuchMethod(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. #### replace(String text) → Description Changes the value of the description. #### toString() → String Returns a string representation of this object. ### Operators #### operator ==(Object other) → bool The equality operator. ``` -------------------------------- ### Run Tests by Name (Plain Text) Source: https://pub.dev/documentation/test/latest/index.html Select and run specific tests by providing a plain text string that their names must contain. ```bash dart test -N "test name" ``` -------------------------------- ### Get Length of Output Source: https://pub.dev/documentation/test/latest/test/StringDescription/length.html Returns the length of the output string. This is an override of the base class getter. ```dart @override int get length => _out.length; ``` -------------------------------- ### startsWith Function Source: https://pub.dev/documentation/test/latest/test/startsWith.html This function creates a matcher that verifies if a given string begins with a specified prefix. ```APIDOC ## startsWith Function ### Description Returns a matcher that matches if the match argument is a string and starts with `prefixString`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Implementation ```dart Matcher startsWith(String prefixString) => _StringStartsWith(prefixString); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Create isMap Constant for Maps Source: https://pub.dev/documentation/test/latest/test/isMap-constant.html Use this constant to create a TypeMatcher for Map objects. No additional setup is required. ```typescript const isMap = TypeMatcher(); ``` -------------------------------- ### OnPlatform Class Source: https://pub.dev/documentation/test/latest/test/OnPlatform-class.html Details about the OnPlatform class, its constructor, properties, and methods. ```APIDOC ## OnPlatform class An annotation for platform-specific customizations for a test suite. See the README. ### Annotations * @Target.new({TargetKind.library}) ### Constructors #### OnPlatform(Map annotationsByPlatform) This is the constructor for the OnPlatform class. ### Properties #### annotationsByPlatform → Map * Type: Map * Description: Stores annotations specific to each platform. #### hashCode → int * Type: int * Description: The hash code for this object. * Inherited: Yes #### runtimeType → Type * Type: Type * Description: A representation of the runtime type of the object. * Inherited: Yes ### Methods #### noSuchMethod(Invocation invocation) → dynamic * Description: Invoked when a nonexistent method or property is accessed. * Inherited: Yes #### toString() → String * Description: A string representation of this object. * Inherited: Yes ### Operators #### operator ==(Object other) → bool * Description: The equality operator. * Inherited: Yes ``` -------------------------------- ### Get Description of Matcher Source: https://pub.dev/documentation/test/latest/test/StreamMatcher/description.html This property returns the description of the matcher. It's typically used in testing to explain what a matcher should assert. ```dart String get description; ``` -------------------------------- ### Run Tests by Name (Regex) Source: https://pub.dev/documentation/test/latest/index.html Select and run specific tests by providing a regular expression that matches their description, including group descriptions. ```bash dart test -n "test name" ``` -------------------------------- ### Run Dart Tests from Source Source: https://pub.dev/documentation/test/latest/index.html Compile and run VM tests directly from source code instead of using the default kernel compilation. This can be combined with platform selectors. ```bash dart test -c source ``` ```bash dart test -c vm:source ``` -------------------------------- ### isNotNaN Matcher Implementation Source: https://pub.dev/documentation/test/latest/test/isNotNaN-constant.html This constant is used to create a matcher that verifies a value is not NaN. It requires no specific setup beyond its declaration. ```dart const Matcher isNotNaN = _IsNotNaN(); ``` -------------------------------- ### Describe Abstract Method Source: https://pub.dev/documentation/test/latest/test/Matcher/describe.html Builds a textual description of the matcher. This is an abstract method. ```java Description describe(Description description); ``` -------------------------------- ### Get Test Suite Tags Source: https://pub.dev/documentation/test/latest/test/Tags/tags.html Retrieves the set of tags for the test suite. Ensure the internal _tags variable is properly managed. ```dart Set get tags => _tags.toSet(); ``` -------------------------------- ### addAll Abstract Method Source: https://pub.dev/documentation/test/latest/test/Description/addAll.html The addAll method is used to add a description of an Iterable list, with appropriate start and end markers and inter-element separator. ```APIDOC ## addAll abstract method ### Description This method is used to add a description of an Iterable `list`, with appropriate `start` and `end` markers and inter-element `separator`. ### Method N/A (Abstract Method Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **start** (String) - Description of the starting marker. - **separator** (String) - Description of the separator between elements. - **end** (String) - Description of the ending marker. - **list** (Iterable) - The iterable collection of elements to add. ### Request Example None (Abstract Method) ### Response #### Success Response (N/A) None (Abstract Method) #### Response Example None (Abstract Method) ``` -------------------------------- ### Methods Source: https://pub.dev/documentation/test/latest/test/isInstanceOf-class.html Details on the methods provided by the isInstanceOf class, including inherited methods. ```APIDOC ## Methods describe(Description description) → Description Builds a textual description of the matcher. inherited describeMismatch(dynamic item, Description mismatchDescription, Map matchState, bool verbose) → Description Builds a textual description of a specific mismatch. inherited having(Object? feature(T), String description, dynamic matcher) → TypeMatcher Returns a new TypeMatcher that validates the existing type as well as a specific `feature` of the object with the provided `matcher`. inherited matches(Object? item, Map matchState) → bool Does the matching of the actual vs expected values. inherited noSuchMethod(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. inherited toString() → String A string representation of this object. inherited ``` -------------------------------- ### internalBootstrapVmTest Source: https://pub.dev/documentation/test/latest/bootstrap_vm Bootstraps a VM test to communicate with the test runner over an isolate. ```APIDOC ## internalBootstrapVmTest ### Description Bootstraps a VM test to communicate with the test runner over an isolate. ### Method void ### Parameters #### Path Parameters - **getMain** (Function) - Required - A function that returns the main entry point for the test. - **sendPort** (SendPort) - Required - The SendPort to communicate with the test runner. ### Response #### Success Response (200) This function does not return a value. ``` -------------------------------- ### Bootstrap Browser Test Source: https://pub.dev/documentation/test/latest/bootstrap_browser/internalBootstrapBrowserTest.html Use this function to bootstrap a browser test. It requires a function to get the main test suite and an optional stream channel for communication. ```dart void internalBootstrapBrowserTest( Function() getMain, { StreamChannel? testChannel, }) { var channel = serializeSuite( getMain, hidePrints: false, beforeLoad: (suiteChannel) async { var serialized = await suiteChannel('test.browser.mapper').stream.first; if (serialized is! Map) return; setStackTraceMapper(JSStackTraceMapper.deserialize(serialized)!); }, ); (testChannel ?? postMessageChannel()).pipe(channel); } ``` -------------------------------- ### internalBootstrapBrowserTest Source: https://pub.dev/documentation/test/latest/bootstrap_browser Bootstraps a browser test to communicate with the test runner. ```APIDOC ## internalBootstrapBrowserTest ### Description Bootstraps a browser test to communicate with the test runner. ### Method void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Describe Method Source: https://pub.dev/documentation/test/latest/test/CustomMatcher/describe.html This snippet details the `describe` method, which builds a textual description of a matcher. ```APIDOC ## Method describe ### Description Builds a textual description of the matcher. ### Method `describe` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **description** (Description) - Required - The description object to add details to. ### Request Example ```json { "description": "{description_object}" } ``` ### Response #### Success Response (200) - **description** (Description) - The updated description object. #### Response Example ```json { "description": "{updated_description_object}" } ``` ### Implementation ```dart @override Description describe(Description description) => description.add(_featureDescription).add(' ').addDescriptionOf(_matcher); ``` ``` -------------------------------- ### CustomMatcher Class Overview Source: https://pub.dev/documentation/test/latest/test/CustomMatcher-class.html Provides an overview of the CustomMatcher class, its inheritance, and its purpose. ```APIDOC ## CustomMatcher Class A base class for Matcher instances that match based on some feature of the value under test. Derived classes should call the base constructor with a feature name and description, and an instance matcher, and should implement the featureValueOf abstract method. ### Inheritance * Object * Matcher * CustomMatcher ``` -------------------------------- ### addAll Abstract Method Signature Source: https://pub.dev/documentation/test/latest/test/Description/addAll.html This is the abstract method signature for addAll. It is used to add a description of an Iterable list, with appropriate start and end markers and inter-element separator. ```java Description addAll(String start, String separator, String end, Iterable list); ``` -------------------------------- ### Bootstrap Native Test Function Source: https://pub.dev/documentation/test/latest/bootstrap_vm/internalBootstrapNativeTest.html Use this function to bootstrap a native executable test. It communicates with the test runner over a socket and expects exactly two arguments: a host and a port. ```dart void internalBootstrapNativeTest( Function() getMain, List args, ) async { if (args.length != 2) { throw StateError( 'Expected exactly two args, a host and a port, but got $args', ); } var socket = await Socket.connect(args[0], int.parse(args[1])); var platformChannel = MultiChannel(jsonSocketStreamChannel(socket)); var testControlChannel = platformChannel.virtualChannel()..pipe(serializeSuite(getMain)); platformChannel.sink.add(testControlChannel.id); unawaited( platformChannel.stream.forEach((message) { assert(message == 'debug'); debugger(message: 'Paused by test runner'); platformChannel.sink.add('done'); }), ); } ``` -------------------------------- ### Run a Single Dart Test File Source: https://pub.dev/documentation/test/latest/index.html Execute a specific test file using the `dart test` command. Requires Dart SDK 2.10 or later. ```bash dart test path/to/test.dart ``` -------------------------------- ### Select Test Reporter Source: https://pub.dev/documentation/test/latest/index.html Adjust the output format of test results. Options include 'compact', 'expanded', 'github', and 'json'. The 'github' reporter is the default on GitHub Actions. ```bash dart test --reporter=compact ``` ```bash dart test --reporter=expanded ``` ```bash dart test --reporter=github ``` ```bash dart test --reporter=json ``` -------------------------------- ### Understanding noSuchMethod Source: https://pub.dev/documentation/test/latest/fake/Fake/noSuchMethod.html This section explains the purpose of the noSuchMethod method in Dart, which is invoked when a nonexistent method or property is accessed on an object. It covers how dynamic member invocations work and provides examples of its usage. ```APIDOC ## Understanding noSuchMethod ### Description The `noSuchMethod` method in Dart is a special method that gets invoked when a program attempts to access a method or property that does not exist on an object. This allows for dynamic handling of such situations. ### Example of Dynamic Invocation ```dart dynamic object = 1; object.add(42); // This will trigger noSuchMethod on the integer object. ``` ### Customizing Behavior Classes can override `noSuchMethod` to provide custom behavior for invalid dynamic invocations. This can be useful for creating mock objects or implementing flexible APIs. ### Example with MockList ```dart class MockList implements List { @override noSuchMethod(Invocation invocation) { print('Method called: ${invocation.memberName}'); // Optionally, call super.noSuchMethod(invocation) to get the default behavior (throwing an error). // super.noSuchMethod(invocation); } } void main() { MockList().add(42); } ``` ### Return Value If `noSuchMethod` returns a value, that value becomes the result of the original invocation. If the returned value's type is incompatible with the expected return type of the original invocation, a type error will occur. ``` -------------------------------- ### Implement Description Add Method Source: https://pub.dev/documentation/test/latest/test/Description/addDescriptionOf.html This abstract method is used to add a meaningful description of a value. Ensure the value provided is of a compatible type. ```java Description addDescriptionOf(Object? value); ``` -------------------------------- ### Using predicate for Even Number Check Source: https://pub.dev/documentation/test/latest/test/predicate.html Use this example to check if a number is even. The predicate function takes the value and returns true if it's even, otherwise false. An optional description can be provided for clarity. ```dart expect(actual, predicate((v) => (v % 2) == 0, 'is even')); ``` -------------------------------- ### Define a CustomMatcher for Widget Price Source: https://pub.dev/documentation/test/latest/test/CustomMatcher-class.html Extend CustomMatcher to create a matcher for a specific feature, like the price of a Widget. Implement featureValueOf to return the feature to be matched. This example shows how to match a price greater than 0. ```dart class HasPrice extends CustomMatcher { HasPrice(matcher) : super("Widget with price that is", "price", matcher); featureValueOf(actual) => (actual as Widget).price; } ``` ```dart expect(inventoryItem, HasPrice(greaterThan(0))); ``` -------------------------------- ### OnPlatform Constructor Implementation Source: https://pub.dev/documentation/test/latest/test/OnPlatform/OnPlatform.html This is the implementation of the OnPlatform constructor, which initializes the annotationsByPlatform map. ```dart const OnPlatform(this.annotationsByPlatform); ``` -------------------------------- ### Asynchronous Test Example Source: https://pub.dev/documentation/test/latest/index.html Tests written with `async`/`await` are automatically handled. The test runner waits for the returned `Future` to complete before marking the test as finished. Ensure all futures have error handlers to prevent uncaught asynchronous errors. ```dart import 'dart:async'; import 'package:test/test.dart'; void main() { test('Future.value() returns the value', () async { var value = await Future.value(10); expect(value, equals(10)); }); } ``` -------------------------------- ### internalBootstrapNativeTest Source: https://pub.dev/documentation/test/latest/bootstrap_vm Bootstraps a native executable test to communicate with the test runner over a socket. ```APIDOC ## internalBootstrapNativeTest ### Description Bootstraps a native executable test to communicate with the test runner over a socket. ### Method void ### Parameters #### Path Parameters - **getMain** (Function) - Required - A function that returns the main entry point for the test. - **args** (List) - Required - A list of string arguments to be passed to the test. ### Response #### Success Response (200) This function does not return a value. ``` -------------------------------- ### Implement spawnHybridCode Function Source: https://pub.dev/documentation/test/latest/test/spawnHybridCode.html This function spawns a VM isolate using the provided dartCode. It converts the dartCode into a data URI and then calls a private _spawn method. The spawned isolate communicates via a StreamChannel. ```dart StreamChannel spawnHybridCode( String dartCode, { Object? message, bool stayAlive = false, }) { var uri = Uri.dataFromString( dartCode, encoding: utf8, mimeType: 'application/dart', ); return _spawn(uri.toString(), message, stayAlive: stayAlive); } ``` -------------------------------- ### StreamMatcher Constructor Source: https://pub.dev/documentation/test/latest/test/StreamMatcher/StreamMatcher.html Creates a new StreamMatcher described by `description` that matches events with `matchQueue`. ```APIDOC ## StreamMatcher Constructor ### Description Creates a new StreamMatcher described by `description` that matches events with `matchQueue`. The `matchQueue` callback is used to implement StreamMatcher.matchQueue, and should follow all the guarantees of that method. In particular: * If it matches successfully, it should return `null` and possibly consume events. * If it fails to match, consume no events and return a description of the failure. * The description should be in past tense. * The description should be grammatically valid when used after "the stream"—"emitted the wrong events", for example. The `matchQueue` callback may return the empty string to indicate a failure if it has no information to add beyond the description of the failure and the events actually emitted by the stream. The `description` should be in the subjunctive mood. This means that it should be grammatically valid when used after the word "should". For example, it might be "emit the right events". ### Method Factory Constructor ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart // Example usage of the StreamMatcher constructor final matcher = StreamMatcher( (queue) async { // Your matching logic here // Return null on success, or a String description on failure return null; }, 'emit the right events', // Description in subjunctive mood ); ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Abstract Method: describe Source: https://pub.dev/documentation/test/latest/test/Matcher/describe.html This endpoint describes the abstract method 'describe' which is used to build a textual description. ```APIDOC ## Abstract Method: describe ### Description Builds a textual description of the matcher. ### Method ABSTRACT ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **description** (Description) - Required - The description object to build upon. ### Request Example ```json { "description": "..." } ``` ### Response #### Success Response (200) - **Description** (Description) - The textual description built. #### Response Example ```json { "description": "..." } ``` ``` -------------------------------- ### Matcher Constructor Source: https://pub.dev/documentation/test/latest/test/Matcher/Matcher.html This section describes the constructor for the Matcher class. ```APIDOC ## Matcher Constructor ### Description This is the constructor for the Matcher class. ### Method Constructor ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Implementation ```dart const Matcher(); ``` ``` -------------------------------- ### Matcher Class Overview Source: https://pub.dev/documentation/test/latest/test/Matcher-class.html Provides an overview of the abstract Matcher class, its purpose, and requirements for subclasses. ```APIDOC ## Matcher Class Abstract The base class for all matchers. `matches` and `describe` must be implemented by subclasses. Subclasses can override `describeMismatch` if a more specific description is required when the matcher fails. ### Constructors * **Matcher()** ### Properties * **hashCode** (int) - The hash code for this object. (inherited) * **runtimeType** (Type) - A representation of the runtime type of the object. (inherited) ### Methods * **describe**(Description description) → Description Builds a textual description of the matcher. * **describeMismatch**(dynamic item, Description mismatchDescription, Map matchState, bool verbose) → Description Builds a textual description of a specific mismatch. * **matches**(dynamic item, Map matchState) → bool Does the matching of the actual vs expected values. * **noSuchMethod**(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. (inherited) * **toString**() → String A string representation of this object. (inherited) ### Operators * **operator ==**(Object other) → bool The equality operator. (inherited) ``` -------------------------------- ### StringDescription Constructors Source: https://pub.dev/documentation/test/latest/test/StringDescription-class.html Information about the constructors available for the StringDescription class. ```APIDOC ## Constructors ### StringDescription([String init = '']) Initialize the description with initial contents `init`. ``` -------------------------------- ### Isolate Spawning Utilities Source: https://pub.dev/documentation/test/latest/test Utilities for spawning isolates for concurrent execution. ```APIDOC ## spawnHybridCode(String dartCode, {Object? message, bool stayAlive = false}) ### Description Spawns a VM isolate that runs the given `dartCode`, which is loaded as the contents of a Dart library. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) StreamChannel #### Response Example N/A ## spawnHybridUri(Object uri, {Object? message, bool stayAlive = false}) ### Description Spawns a VM isolate for the given `uri`, which may be a Uri or a String. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) StreamChannel #### Response Example N/A ``` -------------------------------- ### Utility Functions Source: https://pub.dev/documentation/test/latest/test A collection of utility functions for state management, string manipulation, and asynchronous operations. ```APIDOC ## addStateInfo /websites/pub_dev_test ### Description Useful utility for nesting match states. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) N/A #### Response Example None ``` ```APIDOC ## addTearDown /websites/pub_dev_test ### Description Registers a function to be run after the current test. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) N/A #### Response Example None ``` ```APIDOC ## collapseWhitespace /websites/pub_dev_test ### Description Utility function to collapse whitespace runs to single spaces and strip leading/trailing whitespace. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (String) Returns the processed string. #### Response Example None ``` ```APIDOC ## escape /websites/pub_dev_test ### Description Returns `str` with all whitespace characters represented as their escape sequences. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (String) Returns the escaped string. #### Response Example None ``` -------------------------------- ### internalBootstrapBrowserTest Function Source: https://pub.dev/documentation/test/latest/bootstrap_browser/internalBootstrapBrowserTest.html Bootstraps a browser test to communicate with the test runner. ```APIDOC ## internalBootstrapBrowserTest Function ### Description Bootstraps a browser test to communicate with the test runner. ### Method N/A (This is a function definition, not an API endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **getMain** (Function) - Required - A function that returns the main test suite. - **testChannel** (StreamChannel?) - Optional - A stream channel for communication. If not provided, a default channel is used. ### Implementation ```dart void internalBootstrapBrowserTest( Function getMain(), { StreamChannel? testChannel, }) { var channel = serializeSuite( getMain, hidePrints: false, beforeLoad: (suiteChannel) async { var serialized = await suiteChannel('test.browser.mapper').stream.first; if (serialized is! Map) return; setStackTraceMapper(JSStackTraceMapper.deserialize(serialized)!); }, ); (testChannel ?? postMessageChannel()).pipe(channel); } ``` ``` -------------------------------- ### Implement Describe Method for Matchers Source: https://pub.dev/documentation/test/latest/test/Throws/describe.html Use this method to build a textual description of a matcher. It handles cases where the internal matcher is null by adding 'throws', or adds 'throws ' followed by the description of the internal matcher if it exists. ```dart @override Description describe(Description description) { if (_matcher == null) { return description.add('throws'); } else { return description.add('throws ').addDescriptionOf(_matcher); } } ``` -------------------------------- ### Annotations and Utilities Source: https://pub.dev/documentation/test/latest/test Documentation for annotations and utility classes used in testing. ```APIDOC ## Annotations and Utilities ### Description Provides annotations for controlling test behavior and utility classes for test management. ### Classes - **OnPlatform**: Annotation for platform-specific test configurations. - **Retry**: Annotation to mark a test suite for retries. - **Skip**: Annotation to mark a test suite as skipped. - **Tags**: Annotation for applying user-defined tags to test suites. - **TestLocation**: Represents the location of a test or group. - **TestOn**: Annotation indicating supported platforms for a test suite. - **Timeout**: Represents modifications to the default test timeout. ``` -------------------------------- ### Custom HTML Template Configuration Source: https://pub.dev/documentation/test/latest/index.html Configure a shared HTML template for multiple tests using 'custom_html_template_path'. Use '{{testScript}}' for script insertion and '{{testName}}' for the test filename. ```yaml custom_html_template_path: html_template.html.tpl ``` ```html {{testName}} Test {{testScript}} // ... ``` -------------------------------- ### OnPlatform Constructor Source: https://pub.dev/documentation/test/latest/test/OnPlatform/OnPlatform.html The OnPlatform constructor is used to create an instance of the OnPlatform class, which holds annotations specific to different platforms. ```APIDOC ## OnPlatform Constructor ### Description Initializes a new instance of the OnPlatform class. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ## Implementation ```dart const OnPlatform(this.annotationsByPlatform); ``` ### Parameters - **annotationsByPlatform** (Map) - Required - A map where keys are platform identifiers (String) and values are their corresponding annotations (dynamic). ``` -------------------------------- ### Implement describeMismatch Method Source: https://pub.dev/documentation/test/latest/test/CustomMatcher/describeMismatch.html This method builds a textual description of a specific mismatch. It checks for custom exceptions and their stack traces, or describes the feature and its inner matcher's description. Use this to provide detailed failure information. ```dart @override Description describeMismatch( Object? item, Description mismatchDescription, Map matchState, bool verbose, ) { if (matchState['custom.exception'] != null) { mismatchDescription .add('threw ') .addDescriptionOf(matchState['custom.exception']) .add('\n') .add(matchState['custom.stack'].toString()); return mismatchDescription; } mismatchDescription .add('has ') .add(_featureName) .add(' with value ') .addDescriptionOf(matchState['custom.feature']); var innerDescription = StringDescription(); _matcher.describeMismatch( matchState['custom.feature'], innerDescription, matchState['state'] as Map, verbose, ); if (innerDescription.length > 0) { mismatchDescription.add(' which ').add(innerDescription.toString()); } return mismatchDescription; } ``` -------------------------------- ### Constructors Source: https://pub.dev/documentation/test/latest/test/isInstanceOf-class.html Details about the constructors available for the isInstanceOf class. ```APIDOC ## Constructors isInstanceOf() const ``` -------------------------------- ### Implement Description Add Method Source: https://pub.dev/documentation/test/latest/test/StringDescription/add.html Appends the given text to the description. Returns the Description object for chaining. ```dart @override Description add(String text) { _out.write(text); return this; } ``` -------------------------------- ### Matcher same(Object? expected) Source: https://pub.dev/documentation/test/latest/test/same.html Creates a Matcher that matches if the value is the same instance as `expected`, using the `identical` comparison. ```APIDOC ## Matcher same(Object? expected) ### Description Returns a matcher that matches if the value is the same instance as `expected`, using `identical`. ### Method N/A (This is a function definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Implementation ```dart Matcher same(Object? expected) => _IsSameAs(expected); ``` ```