diff --git a/analysis_options.yaml b/analysis_options.yaml index 6a7f4863..1cb2c624 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,6 +1,10 @@ -include: package:lints/recommended.yaml +include: package:dart_flutter_team_lints/analysis_options.yaml analyzer: + exclude: + - test/**.mocks.dart + errors: + lines_longer_than_80_chars: ignore language: strict-casts: true diff --git a/example/build_extensions/example.dart b/example/build_extensions/example.dart index ddda0654..e34fe2d4 100644 --- a/example/build_extensions/example.dart +++ b/example/build_extensions/example.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +// ignore_for_file: unreachable_from_main + import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:test_api/scaffolding.dart'; @@ -30,7 +32,7 @@ class Dog { @GenerateNiceMocks([MockSpec()]) void main() { test('Verify some dog behaviour', () async { - MockDog mockDog = MockDog(); + var mockDog = MockDog(); when(mockDog.eatFood(any)); mockDog.eatFood('biscuits'); diff --git a/example/example.dart b/example/example.dart index ead196c5..511136a7 100644 --- a/example/example.dart +++ b/example/example.dart @@ -1,3 +1,5 @@ +// ignore_for_file: unreachable_from_main + import 'dart:async'; import 'package:mockito/annotations.dart'; @@ -229,7 +231,7 @@ void main() { final cat = FakeCat(); cat.eatFood('Milk'); // Prints 'Fake eat Milk'. - expect(() => cat.sleep(), throwsUnimplementedError); + expect(cat.sleep, throwsUnimplementedError); }); test('Relaxed mock class', () { diff --git a/example/iss/iss.dart b/example/iss/iss.dart index 9a8ad9f6..ee211225 100644 --- a/example/iss/iss.dart +++ b/example/iss/iss.dart @@ -41,9 +41,10 @@ class IssLocator { // at this moment. final uri = Uri.parse('http://api.open-notify.org/iss-now.json'); final rs = await client.get(uri); - final data = jsonDecode(rs.body); - final latitude = double.parse(data['iss_position']['latitude'] as String); - final longitude = double.parse(data['iss_position']['longitude'] as String); + final data = jsonDecode(rs.body) as Map; + final position = data['iss_position'] as Map; + final latitude = double.parse(position['latitude'] as String); + final longitude = double.parse(position['longitude'] as String); _position = Point(latitude, longitude); } } diff --git a/example/iss/iss_test.dart b/example/iss/iss_test.dart index 1d241218..8b2d9de1 100644 --- a/example/iss/iss_test.dart +++ b/example/iss/iss_test.dart @@ -27,8 +27,8 @@ void main() { // verify the calculated distance between them. group('Spherical distance', () { test('London - Paris', () { - final london = Point(51.5073, -0.1277); - final paris = Point(48.8566, 2.3522); + final london = const Point(51.5073, -0.1277); + final paris = const Point(48.8566, 2.3522); final d = sphericalDistanceKm(london, paris); // London should be approximately 343.5km // (+/- 0.1km) from Paris. @@ -36,8 +36,8 @@ void main() { }); test('San Francisco - Mountain View', () { - final sf = Point(37.783333, -122.416667); - final mtv = Point(37.389444, -122.081944); + final sf = const Point(37.783333, -122.416667); + final mtv = const Point(37.389444, -122.081944); final d = sphericalDistanceKm(sf, mtv); // San Francisco should be approximately 52.8km // (+/- 0.1km) from Mountain View. @@ -52,8 +52,8 @@ void main() { // second predefined location. This test runs asynchronously. group('ISS spotter', () { test('ISS visible', () async { - final sf = Point(37.783333, -122.416667); - final mtv = Point(37.389444, -122.081944); + final sf = const Point(37.783333, -122.416667); + final mtv = const Point(37.389444, -122.081944); final IssLocator locator = MockIssLocator(); // Mountain View should be visible from San Francisco. when(locator.currentPosition).thenReturn(sf); @@ -63,8 +63,8 @@ void main() { }); test('ISS not visible', () async { - final london = Point(51.5073, -0.1277); - final mtv = Point(37.389444, -122.081944); + final london = const Point(51.5073, -0.1277); + final mtv = const Point(37.389444, -122.081944); final IssLocator locator = MockIssLocator(); // London should not be visible from Mountain View. when(locator.currentPosition).thenReturn(london); diff --git a/lib/src/builder.dart b/lib/src/builder.dart index 5abd5d96..61058b7f 100644 --- a/lib/src/builder.dart +++ b/lib/src/builder.dart @@ -42,11 +42,12 @@ import 'package:build/build.dart'; import 'package:code_builder/code_builder.dart' hide refer; import 'package:collection/collection.dart'; import 'package:dart_style/dart_style.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/src/version.dart'; import 'package:path/path.dart' as p; import 'package:source_gen/source_gen.dart'; +import '../annotations.dart'; +import 'version.dart'; + /// For a source Dart library, generate the mocks referenced therein. /// /// Given an input library, 'foo.dart', this builder will search the top-level @@ -106,31 +107,33 @@ class MockBuilder implements Builder { // These comments are added after import directives; leading newlines // are necessary. Individual rules are still ignored to preserve backwards // compatibility with older versions of Dart. - b.body.add(Code('\n\n// ignore_for_file: type=lint\n')); - b.body.add(Code('// ignore_for_file: avoid_redundant_argument_values\n')); + b.body.add(const Code('\n\n// ignore_for_file: type=lint\n')); + b.body.add( + const Code('// ignore_for_file: avoid_redundant_argument_values\n')); // We might generate a setter without a corresponding getter. - b.body.add(Code('// ignore_for_file: avoid_setters_without_getters\n')); + b.body.add( + const Code('// ignore_for_file: avoid_setters_without_getters\n')); // We don't properly prefix imported class names in doc comments. - b.body.add(Code('// ignore_for_file: comment_references\n')); + b.body.add(const Code('// ignore_for_file: comment_references\n')); // We might import a deprecated library, or implement a deprecated class. - b.body.add(Code('// ignore_for_file: deprecated_member_use\n')); - b.body.add(Code( + b.body.add(const Code('// ignore_for_file: deprecated_member_use\n')); + b.body.add(const Code( '// ignore_for_file: deprecated_member_use_from_same_package\n')); // We might import a package's 'src' directory. - b.body.add(Code('// ignore_for_file: implementation_imports\n')); + b.body.add(const Code('// ignore_for_file: implementation_imports\n')); // `Mock.noSuchMethod` is `@visibleForTesting`, but the generated code is // not always in a test directory; the Mockito `example/iss` tests, for // example. - b.body.add(Code( + b.body.add(const Code( '// ignore_for_file: invalid_use_of_visible_for_testing_member\n')); - b.body.add(Code('// ignore_for_file: must_be_immutable\n')); - b.body.add(Code('// ignore_for_file: prefer_const_constructors\n')); + b.body.add(const Code('// ignore_for_file: must_be_immutable\n')); + b.body.add(const Code('// ignore_for_file: prefer_const_constructors\n')); // The code_builder `asA` API unconditionally adds defensive parentheses. - b.body.add(Code('// ignore_for_file: unnecessary_parenthesis\n')); + b.body.add(const Code('// ignore_for_file: unnecessary_parenthesis\n')); // The generator appends a suffix to fake classes - b.body.add(Code('// ignore_for_file: camel_case_types\n')); + b.body.add(const Code('// ignore_for_file: camel_case_types\n')); // The generator has to occasionally implement sealed classes - b.body.add(Code('// ignore_for_file: subtype_of_sealed_class\n\n')); + b.body.add(const Code('// ignore_for_file: subtype_of_sealed_class\n\n')); b.body.addAll(mockLibraryInfo.fakeClasses); b.body.addAll(mockLibraryInfo.mockClasses); }); @@ -329,8 +332,8 @@ class _TypeVisitor extends RecursiveElementVisitor { if (!alreadyVisitedElement) { type.element.typeParameters.forEach(visitTypeParameterElement); - final toStringMethod = - type.element.lookUpMethod('toString', type.element.library); + final toStringMethod = type.element.augmented + .lookUpMethod(name: 'toString', library: type.element.library); if (toStringMethod != null && toStringMethod.parameters.isNotEmpty) { // In a Fake class which implements a class which overrides `toString` // with additional (optional) parameters, we must also override @@ -594,9 +597,7 @@ class _MockTargetGatherer { var type = _determineDartType(typeToMock, entryLib.typeProvider); final mockTypeArguments = mockType?.typeArguments; if (mockTypeArguments != null) { - final typeName = - type.alias?.element.getDisplayString(withNullability: false) ?? - 'type $type'; + final typeName = type.alias?.element.getDisplayString() ?? 'type $type'; final typeArguments = type.alias?.typeArguments ?? type.typeArguments; // Check explicit type arguments for unknown types that were // turned into `dynamic` by the analyzer. @@ -1593,7 +1594,7 @@ class _MockClassInfo { } } if (type.returnType is analyzer.VoidType) { - b.body = Code(''); + b.body = const Code(''); } else { b.body = _dummyValue(type.returnType, invocation).code; } @@ -1688,8 +1689,8 @@ class _MockClassInfo { ..initializers.add(refer('super') .call([refer('parent'), refer('parentInvocation')]).code))); - final toStringMethod = - elementToFake.lookUpMethod('toString', elementToFake.library); + final toStringMethod = elementToFake.augmented + .lookUpMethod(name: 'toString', library: elementToFake.library); if (toStringMethod != null && toStringMethod.parameters.isNotEmpty) { // If [elementToFake] includes an overriding `toString` implementation, // we need to include an implementation which matches the signature. @@ -1849,7 +1850,7 @@ class _MockClassInfo { // TODO(srawlins): It seems like this might be revivable, but Angular // does not revive Types; we should investigate this if users request it. final type = object.toTypeValue()!; - final typeStr = type.getDisplayString(withNullability: false); + final typeStr = type.getDisplayString(); throw _ReviveException('default value is a Type: $typeStr.'); } else { // If [constant] is not null, a literal, or a type, then it must be an @@ -2177,7 +2178,7 @@ class _MockClassInfo { ..isNullable = forceNullable || typeSystem.isNullable(type)); } else { return referImported( - type.getDisplayString(withNullability: false), + type.getDisplayString(), _typeImport(type.element), ); } @@ -2286,7 +2287,7 @@ class _AvoidConflictsAllocator implements Allocator { /// A [MockBuilder] instance for use by `build.yaml`. Builder buildMocks(BuilderOptions options) { final buildExtensions = options.config['build_extensions']; - if (buildExtensions == null) return MockBuilder(); + if (buildExtensions == null) return const MockBuilder(); if (buildExtensions is! Map) { throw ArgumentError( 'build_extensions should be a map from inputs to outputs'); diff --git a/lib/src/dummies.dart b/lib/src/dummies.dart index 0ac18657..7d12fdbf 100644 --- a/lib/src/dummies.dart +++ b/lib/src/dummies.dart @@ -134,7 +134,7 @@ List _defaultDummies = [ [], {}, {}, - Stream.empty(), + const Stream.empty(), SplayTreeSet(), SplayTreeMap(), ]; @@ -155,6 +155,7 @@ T? dummyValueOrNull(Object parent, Invocation invocation) { T dummyValue(Object parent, Invocation invocation) { final value = dummyValueOrNull(parent, invocation); if (value is T) return value; + // ignore: only_throw_errors throw MissingDummyValueError(T); } diff --git a/lib/src/invocation_matcher.dart b/lib/src/invocation_matcher.dart index d809c19a..8f6d91d2 100644 --- a/lib/src/invocation_matcher.dart +++ b/lib/src/invocation_matcher.dart @@ -14,7 +14,7 @@ import 'package:collection/collection.dart'; import 'package:matcher/matcher.dart'; -import 'package:mockito/src/mock.dart'; +import 'mock.dart'; /// Returns a matcher that expects an invocation that matches arguments given. /// @@ -130,7 +130,7 @@ class _InvocationMatcher implements Matcher { // Specifically, if a Matcher is passed as an argument, we'd like to get an // error like "Expected fly(miles: > 10), Actual: fly(miles: 5)". @override - Description describeMismatch(item, Description d, _, __) { + Description describeMismatch(dynamic item, Description d, _, __) { if (item is Invocation) { d = d.add('Does not match '); return _describeInvocation(d, item); @@ -139,7 +139,7 @@ class _InvocationMatcher implements Matcher { } @override - bool matches(item, _) => + bool matches(dynamic item, _) => item is Invocation && _invocation.memberName == item.memberName && _invocation.isSetter == item.isSetter && @@ -156,7 +156,7 @@ class _MatcherEquality extends DeepCollectionEquality /* */ { const _MatcherEquality(); @override - bool equals(e1, e2) { + bool equals(Object? e1, Object? e2) { // All argument matches are wrapped in `ArgMatcher`, so we have to unwrap // them into the raw `Matcher` type in order to finish our equality checks. if (e1 is ArgMatcher) { diff --git a/lib/src/mock.dart b/lib/src/mock.dart index d99b39db..84db8d13 100644 --- a/lib/src/mock.dart +++ b/lib/src/mock.dart @@ -22,12 +22,13 @@ import 'dart:collection'; import 'package:matcher/expect.dart'; import 'package:meta/meta.dart'; -import 'package:mockito/src/call_pair.dart'; -import 'package:mockito/src/dummies.dart' show resetDummyBuilders; -import 'package:mockito/src/invocation_matcher.dart'; // ignore: deprecated_member_use import 'package:test_api/fake.dart'; +import 'call_pair.dart'; +import 'dummies.dart' show resetDummyBuilders; +import 'invocation_matcher.dart'; + /// Whether a [when] call is "in progress." /// /// Since [when] is a getter, this is `true` immediately after [when] returns, @@ -195,7 +196,7 @@ mixin class Mock { int get hashCode => _givenHashCode ?? 0; @override - bool operator ==(other) => (_givenHashCode != null && other is Mock) + bool operator ==(Object other) => (_givenHashCode != null && other is Mock) ? _givenHashCode == other._givenHashCode : identical(this, other); @@ -392,8 +393,7 @@ class _InvocationForMatchedArguments extends Invocation { // by a stored value in [_storedNamedArgs]. static Map _reconstituteNamedArgs(Invocation invocation) { final namedArguments = {}; - final storedNamedArgSymbols = - _storedNamedArgs.keys.map((name) => Symbol(name)); + final storedNamedArgSymbols = _storedNamedArgs.keys.map(Symbol.new); // Iterate through [invocation]'s named args, validate them, and add them // to the return map. @@ -509,13 +509,13 @@ T named(T mock, {String? name, int? hashCode}) => mock .._givenHashCode = hashCode; /// Clear stubs of, and collected interactions with [mock]. -void reset(var mock) { +void reset(Mock mock) { mock._realCalls.clear(); mock._responses.clear(); } /// Clear the collected interactions with [mock]. -void clearInteractions(var mock) { +void clearInteractions(Mock mock) { mock._realCalls.clear(); } @@ -557,6 +557,7 @@ class PostExpectation { /// Store an exception to throw when this method stub is called. void thenThrow(Object throwable) { return _completeWhen((Invocation _) { + // ignore: only_throw_errors throw throwable; }); } @@ -668,7 +669,7 @@ class InvocationMatcher { return true; } - bool isMatchingArg(roleArg, actArg) { + bool isMatchingArg(dynamic roleArg, dynamic actArg) { if (roleArg is ArgMatcher) { return roleArg.matcher.matches(actArg, {}); } else { @@ -967,7 +968,6 @@ class VerificationResult { @Deprecated( 'captured should be considered final - assigning this field may be ' 'removed as early as Mockito 5.0.0') - // ignore: unnecessary_getters_setters set captured(List captured) => _captured = captured; /// The number of calls matched in this verification. @@ -1133,6 +1133,7 @@ List Function(List recordedInvocations) matchedCalls.add(matched.realCall); verificationResults.add(VerificationResult._(1, matched.capturedArgs)); time = matched.realCall.timeStamp; + // ignore: avoid_catching_errors } on StateError { final mocks = tmpVerifyCalls.map((vc) => vc.mock).toSet(); final allInvocations = @@ -1154,14 +1155,14 @@ List Function(List recordedInvocations) }; } -void _throwMockArgumentError(String method, var nonMockInstance) { +void _throwMockArgumentError(String method, dynamic nonMockInstance) { if (nonMockInstance == null) { throw ArgumentError('$method was called with a null argument'); } throw ArgumentError('$method must only be given a Mock object'); } -void verifyNoMoreInteractions(var mock) { +void verifyNoMoreInteractions(dynamic mock) { if (mock is Mock) { final unverified = mock._realCalls.where((inv) => !inv.verified).toList(); if (unverified.isNotEmpty) { @@ -1172,7 +1173,7 @@ void verifyNoMoreInteractions(var mock) { } } -void verifyZeroInteractions(var mock) { +void verifyZeroInteractions(dynamic mock) { if (mock is Mock) { if (mock._realCalls.isNotEmpty) { fail('No interaction expected, but following found: ' diff --git a/pubspec.yaml b/pubspec.yaml index 5cd36f6b..c7b3f041 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -24,7 +24,7 @@ dev_dependencies: build_runner: ^2.0.0 build_test: ^2.0.0 build_web_compilers: '>=3.0.0 <5.0.0' + dart_flutter_team_lints: ^2.1.1 http: ^1.0.0 - lints: ^3.0.0 package_config: ^2.0.0 test: ^1.16.0 diff --git a/test/builder/auto_mocks_test.dart b/test/builder/auto_mocks_test.dart index 83631677..ad385616 100644 --- a/test/builder/auto_mocks_test.dart +++ b/test/builder/auto_mocks_test.dart @@ -13,6 +13,8 @@ // limitations under the License. @TestOn('vm') +library; + import 'dart:convert' show utf8; import 'package:build/build.dart'; @@ -101,7 +103,7 @@ void main() { languageVersion: LanguageVersion(3, 3)) ]); - await testBuilder(buildMocks(BuilderOptions({})), sourceAssets, + await testBuilder(buildMocks(const BuilderOptions({})), sourceAssets, writer: writer, packageConfig: packageConfig); final mocksAsset = AssetId('foo', 'test/foo_test.mocks.dart'); return utf8.decode(writer.assets[mocksAsset]!); @@ -3753,7 +3755,7 @@ void main() { }); } -TypeMatcher> _containsAllOf(a, [b]) => decodedMatches( +TypeMatcher> _containsAllOf(Object? a, [Object? b]) => decodedMatches( b == null ? allOf(contains(a)) : allOf(contains(a), contains(b))); /// Expect that [testBuilder], given [assets], in a package which has opted into @@ -3774,13 +3776,13 @@ void _expectBuilderThrows({ expect( () => withEnabledExperiments( () => testBuilder( - buildMocks(BuilderOptions({})), + buildMocks(const BuilderOptions({})), assets, packageConfig: packageConfig, ), enabledExperiments, ), - throwsA(TypeMatcher() + throwsA(const TypeMatcher() .having((e) => e.message, 'message', message))); } diff --git a/test/builder/custom_mocks_test.dart b/test/builder/custom_mocks_test.dart index 2b987cf3..8024bce8 100644 --- a/test/builder/custom_mocks_test.dart +++ b/test/builder/custom_mocks_test.dart @@ -13,6 +13,8 @@ // limitations under the License. @TestOn('vm') +library; + import 'dart:convert' show utf8; import 'package:build/build.dart'; @@ -21,7 +23,7 @@ import 'package:mockito/src/builder.dart'; import 'package:package_config/package_config.dart'; import 'package:test/test.dart'; -Builder buildMocks(BuilderOptions options) => MockBuilder(); +Builder buildMocks(BuilderOptions options) => const MockBuilder(); const annotationsAsset = { 'mockito|lib/annotations.dart': ''' @@ -81,11 +83,6 @@ void main() {} ''' }; -const _constructorWithThrowOnMissingStub = ''' -MockFoo() { - _i1.throwOnMissingStub(this); - }'''; - void main() { late InMemoryAssetWriter writer; @@ -97,7 +94,7 @@ void main() { packageUriRoot: Uri.file('/foo/lib/'), languageVersion: LanguageVersion(3, 3)) ]); - await testBuilder(buildMocks(BuilderOptions({})), sourceAssets, + await testBuilder(buildMocks(const BuilderOptions({})), sourceAssets, writer: writer, packageConfig: packageConfig); final mocksAsset = AssetId('foo', 'test/foo_test.mocks.dart'); return utf8.decode(writer.assets[mocksAsset]!); @@ -1755,9 +1752,6 @@ void main() { }); } -TypeMatcher> _containsAllOf(a, [b]) => decodedMatches( - b == null ? allOf(contains(a)) : allOf(contains(a), contains(b))); - /// Expect that [testBuilder], given [assets], throws an /// [InvalidMockitoAnnotationException] with a message containing [message]. void _expectBuilderThrows({ @@ -1765,8 +1759,9 @@ void _expectBuilderThrows({ required dynamic /*String|Matcher>*/ message, }) { expect( - () async => await testBuilder(buildMocks(BuilderOptions({})), assets), - throwsA(TypeMatcher() + () async => + await testBuilder(buildMocks(const BuilderOptions({})), assets), + throwsA(const TypeMatcher() .having((e) => e.message, 'message', message))); } diff --git a/test/capture_test.dart b/test/capture_test.dart index 5545e72a..4f8913cb 100644 --- a/test/capture_test.dart +++ b/test/capture_test.dart @@ -34,11 +34,7 @@ void main() { mock = _MockedClass(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('capture', () { test('captureAny should match anything', () { diff --git a/test/end2end/generated_mocks_test.dart b/test/end2end/generated_mocks_test.dart index ca891e9b..32c1610f 100644 --- a/test/end2end/generated_mocks_test.dart +++ b/test/end2end/generated_mocks_test.dart @@ -1,3 +1,5 @@ +// ignore_for_file: inference_failure_on_function_invocation, inference_failure_on_instance_creation + import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; @@ -42,11 +44,7 @@ void main() { fooSub = MockFooSub(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); test('a method with a positional parameter can be stubbed', () { when(foo.positionalParameter(42)).thenReturn('Stubbed'); @@ -150,15 +148,17 @@ void main() { when(foo.namedParameter(x: 42)).thenReturn('Stubbed'); expect( () => foo.namedParameter(x: 43), - throwsA(TypeMatcher().having((e) => e.toString(), - 'toString()', contains('namedParameter({x: 43})'))), + throwsA(const TypeMatcher().having( + (e) => e.toString(), + 'toString()', + contains('namedParameter({x: 43})'))), ); }); test('an unstubbed getter throws', () { expect( () => foo.getter, - throwsA(TypeMatcher() + throwsA(const TypeMatcher() .having((e) => e.toString(), 'toString()', contains('getter'))), ); }); @@ -192,7 +192,7 @@ void main() { baz = MockBazWithUnsupportedMembers(); }); - tearDown(() => resetMockitoState()); + tearDown(resetMockitoState); test('a real method call that returns private type throws', () { expect(() => baz.returnsPrivate(), throwsUnsupportedError); @@ -311,15 +311,13 @@ void main() { when(foo.returnsBar(42)).thenReturn(Bar()); final bar = foo.returnsBar(43); expect( - () => bar.f(), + bar.f, throwsA(isA().having( (e) => e.toString(), 'toString()', contains('returnsBar(43)')))); }); group('a method returning Future', () { final bar = Bar(); - tearDown(() { - resetMockitoState(); - }); + tearDown(resetMockitoState); test('returns a fake future if unstubbed', () { expect(foo.returnsFuture(bar), isA()); }); diff --git a/test/invocation_matcher_test.dart b/test/invocation_matcher_test.dart index baa8838a..7cadab84 100644 --- a/test/invocation_matcher_test.dart +++ b/test/invocation_matcher_test.dart @@ -140,7 +140,7 @@ void main() { abstract class Interface { bool? get value; - set value(value); + set value(bool? value); void say(String text); void eat(String food, {bool? alsoDrink}); void lie([bool? facingDown]); @@ -162,7 +162,7 @@ class Stub implements Interface { } // Inspired by shouldFail() from package:test, which doesn't expose it to users. -void shouldFail(value, Matcher matcher, expected) { +void shouldFail(Invocation value, Matcher matcher, Object? expected) { const reason = 'Expected to fail.'; try { expect(value, matcher); @@ -177,6 +177,6 @@ void shouldFail(value, Matcher matcher, expected) { } } -void shouldPass(value, Matcher matcher) { +void shouldPass(Invocation value, Matcher matcher) { expect(value, matcher); } diff --git a/test/manual_mocks_test.dart b/test/manual_mocks_test.dart index 918c2806..ba946d10 100644 --- a/test/manual_mocks_test.dart +++ b/test/manual_mocks_test.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +// ignore_for_file: unreachable_from_main, inference_failure_on_function_invocation + import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; @@ -84,11 +86,7 @@ void main() { mock = MockedClass(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('when()', () { test( @@ -99,14 +97,14 @@ void main() { expect( () => when(mock.notMockedNonNullableParam((any as dynamic) as int)) .thenReturn('Mock'), - throwsA(TypeMatcher())); + throwsA(const TypeMatcher())); }); test( 'cannot operate on method with non-nullable return type without a ' 'manual mock', () { expect(() => when(mock.notMockedNonNullableReturn()).thenReturn(7), - throwsA(TypeMatcher())); + throwsA(const TypeMatcher())); }); test('should mock method with non-nullable params', () { @@ -169,8 +167,8 @@ void main() { test( 'should throw a TypeError on a call to a function with a non-nullable ' 'return type without a matching stub', () { - expect( - () => mock.nonNullableReturn(43), throwsA(TypeMatcher())); + expect(() => mock.nonNullableReturn(43), + throwsA(const TypeMatcher())); }); test( @@ -178,7 +176,7 @@ void main() { 'using `throwOnMissingStub` behavior', () { throwOnMissingStub(mock); expect(() => mock.nonNullableReturn(43), - throwsA(TypeMatcher())); + throwsA(const TypeMatcher())); }); }); diff --git a/test/mockito_test.dart b/test/mockito_test.dart index 964b8824..3aad5919 100644 --- a/test/mockito_test.dart +++ b/test/mockito_test.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +// ignore_for_file: unreachable_from_main + import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; @@ -68,11 +70,7 @@ void main() { mock = _MockedClass(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('mixin support', () { test('should work', () { @@ -297,7 +295,7 @@ void main() { when(mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect( () => mock.methodWithoutArgs(), - throwsA(TypeMatcher()), + throwsA(const TypeMatcher()), ); }); diff --git a/test/nnbd_support_test.dart b/test/nnbd_support_test.dart index 9a83582e..c43c2a95 100644 --- a/test/nnbd_support_test.dart +++ b/test/nnbd_support_test.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +// ignore_for_file: unreachable_from_main + import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; @@ -36,11 +38,7 @@ void main() { mock = MockFoo(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('Using nSM out of the box,', () { test('nSM returns the dummy value during method stubbing', () { diff --git a/test/until_called_test.dart b/test/until_called_test.dart index 6c96ea23..9aa0cc2e 100644 --- a/test/until_called_test.dart +++ b/test/until_called_test.dart @@ -73,11 +73,7 @@ void main() { mock = _MockedClass(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('untilCalled', () { final streamController = StreamController.broadcast(); diff --git a/test/verify_test.dart b/test/verify_test.dart index 373561d9..f45fb0a6 100644 --- a/test/verify_test.dart +++ b/test/verify_test.dart @@ -74,11 +74,7 @@ void main() { mock = _MockedClass(); }); - tearDown(() { - // In some of the tests that expect an Error to be thrown, Mockito's - // global state can become invalid. Reset it. - resetMockitoState(); - }); + tearDown(resetMockitoState); group('verify', () { test('should verify method without args', () { @@ -184,7 +180,7 @@ void main() { }); test('should throw meaningful errors when verification is interrupted', () { - int badHelper() => throw 'boo'; + int badHelper() => throw Exception('boo'); try { verify(mock.methodWithNamedArgs(42, y: badHelper()));