Skip to content

Instantly share code, notes, and snippets.

@devvspaces
Created October 7, 2022 15:43
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 devvspaces/e6182ae29cf595f68eafa9ac26305794 to your computer and use it in GitHub Desktop.
Save devvspaces/e6182ae29cf595f68eafa9ac26305794 to your computer and use it in GitHub Desktop.
console bank
class BankAccount {
String? accountName;
String? accountNumber;
double accountBalance = 0;
BankAccount(String name, String number){
accountName = name;
// Validate account number
RegExp pattern = RegExp(r'^\d+$');
bool match = pattern.hasMatch(number);
if (!match){
throw "Invalid Account number";
}
accountNumber = number;
}
double getBalance(){
// Get user account balance
return accountBalance;
}
void depositMoney(double amount){
// Add amount to user balance
accountBalance += amount;
print("Money deposited successfully!");
}
void withdrawMoney(double amount){
// Withdraw amount from user balance
if (amount > accountBalance){
print("Insufficient funds!");
return;
}
accountBalance -= amount;
}
}
BankAccount createTestUser(){
// Create user accounts for testing
return BankAccount("Test User", "0902348378");
}
void testCase0(){
// Test for bad account number names
List<String> badNames = ["0902A3G8378", "09023.8378"];
for (String name in badNames){
try{
BankAccount("Test User", name);
} catch(e){
assert(e == "Invalid Account number");
}
}
}
void testCase1(){
var user = createTestUser();
assert(user.getBalance() == 0);
}
void testCase2(){
var user = createTestUser();
user.depositMoney(5000);
assert(user.getBalance() == 5000);
}
void testCase3(){
var user = createTestUser();
// Should print insufficient funds
user.withdrawMoney(5000);
assert(user.getBalance() == 0);
}
void testCase4(){
var user = createTestUser();
user.depositMoney(15000);
user.withdrawMoney(5000);
assert(user.getBalance() == 10000);
}
String? getFunctionName(var func){
// Get the name of the provided function
String name = func.toString();
RegExp pattern = RegExp(r"'\w+'");
return pattern.stringMatch(name);
}
void main() {
var testCases = [testCase0, testCase1, testCase2, testCase3, testCase4];
int failed = 0;
int passed = 0;
// Run test cases
for (final test in testCases){
String? funcName = getFunctionName(test);
print("Running test for $funcName");
try{
test();
} catch(e) {
print("Test failed! ❌\n");
failed++;
continue;
}
print("Test passed! ✅\n");
passed++;
}
double percent = (passed / testCases.length) * 100;
print("======= Completed $percent% ========");
print("Tests passed: $passed");
print("Tests failed: $failed");
print("===============================");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment