Skip to content

Commit b7b94b3

Browse files
authored
throw AssertionError on non-mock implementations (flutter#2324)
1 parent bb604ef commit b7b94b3

File tree

2 files changed

+57
-4
lines changed

2 files changed

+57
-4
lines changed

packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,15 @@ abstract class SharedPreferencesStorePlatform {
2424
/// Platform-specific plugins should set this with their own platform-specific
2525
/// class that extends [SharedPreferencesStorePlatform] when they register themselves.
2626
static set instance(SharedPreferencesStorePlatform value) {
27-
try {
28-
instance._verifyProvidesDefaultImplementations();
29-
_instance = value;
30-
} on NoSuchMethodError catch (_) {}
27+
if (!value.isMock) {
28+
try {
29+
value._verifyProvidesDefaultImplementations();
30+
} on NoSuchMethodError catch (_) {
31+
throw AssertionError(
32+
'Platform interfaces must not be implemented with `implements`');
33+
}
34+
}
35+
_instance = value;
3136
}
3237

3338
static SharedPreferencesStorePlatform _instance =
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Copyright 2017 The Chromium Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter_test/flutter_test.dart';
6+
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
7+
8+
void main() {
9+
TestWidgetsFlutterBinding.ensureInitialized();
10+
11+
group(SharedPreferencesStorePlatform, () {
12+
test('disallows implementing interface', () {
13+
expect(
14+
() {
15+
SharedPreferencesStorePlatform.instance = IllegalImplementation();
16+
},
17+
throwsAssertionError,
18+
);
19+
});
20+
});
21+
}
22+
23+
class IllegalImplementation implements SharedPreferencesStorePlatform {
24+
// Intentionally declare self as not a mock to trigger the
25+
// compliance check.
26+
@override
27+
bool get isMock => false;
28+
29+
@override
30+
Future<bool> clear() {
31+
throw UnimplementedError();
32+
}
33+
34+
@override
35+
Future<Map<String, Object>> getAll() {
36+
throw UnimplementedError();
37+
}
38+
39+
@override
40+
Future<bool> remove(String key) {
41+
throw UnimplementedError();
42+
}
43+
44+
@override
45+
Future<bool> setValue(String valueType, String key, Object value) {
46+
throw UnimplementedError();
47+
}
48+
}

0 commit comments

Comments
 (0)