Added functions & test cases: deleteAccount and getAllAccounts

This commit is contained in:
2024-12-06 13:27:33 +01:00
parent 46b0410bc5
commit 47f9285f37
3 changed files with 121 additions and 0 deletions

View File

@@ -97,4 +97,19 @@ public interface Bank {
* @return the list of all transactions by type
*/
List<Transaction> getTransactionsByType(String account, boolean positive);
/**
* Delets an existing account
* @param account the account to be deleted
* @throws AccountDoesNotExistException
* @throws IOException
*/
void deleteAccount(String account) throws AccountDoesNotExistException, IOException;
/**
* Returns a list of all account names
* @return
*/
List<String> getAllAccounts();
}

View File

@@ -354,6 +354,47 @@ public class PrivateBank implements Bank, JsonSerializer<Transaction>, JsonDeser
return transactions;
}
/**
* Delets an existing account
*
* @param account the account to be deleted
* @throws AccountDoesNotExistException
* @throws IOException
*/
@Override
public void deleteAccount(String account) throws AccountDoesNotExistException, IOException {
if (this.containsAccount(account)) {
// delete account
this.accountsToTransactions.remove(account);
// delete corresponding JSON file
String filename = directoryName + "/" + account + ".json";
File file = new File(filename);
if (!file.delete())
throw new IOException();
} else {
throw new AccountDoesNotExistException();
}
}
/**
* Returns a list of all account names
*
* @return List of all accounts
*/
@Override
public List<String> getAllAccounts() {
List<String> accounts = new ArrayList<>();
this.accountsToTransactions.forEach(
(account, transactions) -> {
accounts.add(account);
}
);
return accounts;
}
/**
* Import Accounts from existing JSON Files
*
@@ -499,4 +540,6 @@ public class PrivateBank implements Bank, JsonSerializer<Transaction>, JsonDeser
return rootObject;
}
}

View File

@@ -429,4 +429,67 @@ public class PrivateBankTest {
AccountAlreadyExistsException.class, () -> privateBank.readAccounts()
);
}
@DisplayName("Delete existing account")
@Order(20)
@Test
public void testDeleteExistingAccount() {
assertDoesNotThrow(
() -> privateBank.createAccount(
"Konto_X",
List.of(
new OutgoingTransfer(
"01.01.2000",
100,
"OutgoingTransfer to Hans",
"Konto_X",
"Hans"
),
new IncomingTransfer(
"01.01.2000",
100,
"IncomingTransfer from Hans",
"Hans",
"Konto_X"
),
new IncomingTransfer(
"01.01.2000",
300,
"IncomingTransfer from Tom",
"Tom",
"Konto_X"
)
)
)
);
assertDoesNotThrow(
() -> privateBank.writeAccount("Konto_X")
);
assertTrue(
() -> privateBank.containsAccount("Konto_X")
);
assertDoesNotThrow(
() -> privateBank.deleteAccount("Konto_X")
);
assertFalse(
() -> privateBank.containsAccount("Konto_X")
);
}
@DisplayName("Delete non existing account")
@Order(21)
@Test
public void testDeleteNonExistingAccount() {
assertThrows(
AccountDoesNotExistException.class, () -> privateBank.deleteAccount("Konto_X")
);
}
}