Created
September 22, 2023 13:18
-
-
Save easylive1989/8d5e65a2af7f3c0f8ab4d99a55f6f12b to your computer and use it in GitHub Desktop.
2023鐵人賽_D8_1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:shared_preferences/shared_preferences.dart'; | |
import 'product.dart'; | |
class MyFavorites { | |
final SharedPreferences _preferences; | |
MyFavorites(SharedPreferences preference) : _preferences = preference; | |
Future<void> add(Product product) async { | |
var favorites = getAll(); | |
favorites.add(product); | |
await _preferences.setStringList("favorites", | |
favorites.map((product) => product.id.toString()).toList()); | |
} | |
List<Product> getAll() { | |
return _preferences | |
.getStringList("favorites") | |
?.map((id) => Product(int.parse(id))) | |
.toList() ?? | |
[]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter_test/flutter_test.dart'; | |
import 'package:mockito/annotations.dart'; | |
import 'package:mockito/mockito.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
import 'my_favorites_test.mocks.dart'; | |
import 'product.dart'; | |
import 'my_favorites.dart'; | |
@GenerateNiceMocks([MockSpec<SharedPreferences>()]) | |
main() { | |
test("add favorite", () { | |
var mockSharedPreferences = MockSharedPreferences(); | |
var myFavorites = MyFavorites(mockSharedPreferences); | |
myFavorites.add(const Product(1)); | |
verify(mockSharedPreferences.setStringList("favorites", ["1"])); | |
}); | |
test("getAll", () { | |
var mockSharedPreferences = MockSharedPreferences(); | |
when(mockSharedPreferences.getStringList("favorites")).thenReturn(["1"]); | |
var myFavorites = MyFavorites(mockSharedPreferences); | |
expect(myFavorites.getAll(), [const Product(1)]); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:equatable/equatable.dart'; | |
class Product extends Equatable { | |
final int id; | |
const Product(this.id); | |
@override | |
List<Object?> get props => [id]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment