Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save easylive1989/a563db36e691d02f8b8175249f1dfa7a to your computer and use it in GitHub Desktop.
Save easylive1989/a563db36e691d02f8b8175249f1dfa7a to your computer and use it in GitHub Desktop.
2023鐵人賽_D7_1
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'purchase_product_service.dart';
import 'product.dart';
import 'wallet.dart';
import 'money_not_enough_exception.dart';
import 'wallet_repository.dart';
import 'product_repository.dart';
import 'purchase_product_service_normal_test.mocks.dart';
@GenerateNiceMocks([MockSpec<ProductRepository>(), MockSpec<WalletRepository>()])
main() {
test("should throw money not enough exception", () {
var mockProductRepository = MockProductRepository();
var mockWalletRepository = MockWalletRepository();
when(mockWalletRepository.get()).thenAnswer((_) async => Wallet(50));
var purchaseProductService = PurchaseProductService(mockProductRepository, mockWalletRepository);
expect(() => purchaseProductService.execute(const Product(100)), throwsA(isA<MoneyNotEnoughException>()));
});
}
class MoneyNotEnoughException implements Exception {}
import 'package:equatable/equatable.dart';
class Product extends Equatable {
final double price;
const Product(this.price);
@override
List<Object?> get props => [price];
}
import 'product.dart';
class ProductRepository {
Future<void> purchase(Product product) async {}
}
import 'product_repository.dart';
import 'wallet_repository.dart';
import 'product.dart';
import 'wallet.dart';
import 'money_not_enough_exception.dart';
class PurchaseProductService {
final ProductRepository productRepository;
final WalletRepository walletRepository;
PurchaseProductService(this.productRepository, this.walletRepository);
Future<void> execute(Product product) async {
var wallet = await _getWallet();
if (product.price > wallet.money) {
throw MoneyNotEnoughException();
}
productRepository.purchase(product);
}
Future<Wallet> _getWallet() async {
return await walletRepository.get();
}
}
class Wallet {
final double money;
Wallet(this.money);
}
import 'wallet.dart';
class WalletRepository {
Future<Wallet> get() async => Wallet(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment