Question

In: Computer Science

java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a...

java code

============

public class BankAccount {
        
        private String accountID;
        private double balance;
        

           /**
              Constructs a bank account with a zero balance
              @param accountID - ID of the Account
           */
           public BankAccount(String accountID)
           {   
              balance = 0;
              this.accountID = accountID;
           }

           /**
              Constructs a bank account with a given balance
              @param initialBalance the initial balance
              @param accountID - ID of the Account
           */
           public BankAccount(double initialBalance, String accountID) 
           {   

                        this.accountID = accountID;
                        balance = initialBalance;
           }
           
           /**
                 * Returns the Account ID
                 * @return the accountID
                 */
                public String getAccountID() {
                        return accountID;
                }
                
                /**
                 * Sets the Account ID
                 * @param accountID
                 */
                public void setAccountID(String accountID) {
                        this.accountID = accountID;
                }

           /**
              Deposits money into the bank account.
              @param amount the amount to deposit
           */
           public void deposit(double amount) 
           {  

                        balance += amount;
           }

           /**
              Withdraws money from the bank account.
              @param amount the amount to withdraw
              @return true if allowed to withdraw
           */
           public boolean withdraw(double amount) 
           {   
                  boolean isAllowed = balance >= amount;
                  if (isAllowed)
                          balance -= amount;
                  return isAllowed;
           }

           /**
              Gets the current balance of the bank account.
              @return the current balance
           */
           public double getBalance()
           {   
              return balance;
           }
          
        }

==========================

You must write tests for the following:

Unit Testing with JUnit 5

You must write tests for the following (which may include Custom Exceptions):

  • BankAccount Class
    • Tests are written such that any deposit that is made greater than 10000 is not accepted.

    • Tests are written such that balance in the BankAccount does not go below 0.

    • Care should be taken for above tests at the time of Initial Deposit and at the time of Withdrawal and future Deposits.

    • Tests should be written such that the Bank AccountID only accepts a string of length 4 with first letter as a character followed by 3 integers, Eg., "A001", is a valid AccountID.

Solutions

Expert Solution

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class BankAccountTest {

        BankAccount b;
        
        @Before
        public void setup() {
                b = new BankAccount("A123");
        }
        
        @Test
        public void testBadDeposit() {
                double bal = b.getBalance();
                
                try {
                        b.deposit(10001);
                        Assert.fail(); // If we reached here, it means no exception came.
                } catch(Exception e) {
                        // we are good here.
                }
                // the balance should remain same, Because more than 10000 should not be accepted.
                assertEquals(bal, b.getBalance(), 0.000001);
        }
        
        @Test
        public void testLowBalance() {
                double bal = b.getBalance();
                assertFalse(b.withdraw(bal + 100));

                // the balance should remain same, Because it can not be negative.
                assertEquals(bal, b.getBalance(), 0.000001);
        }
        
        @Test
        public void testValidId() {
                
                String ids[] = new String[] {"123", "A", null, "", "AAAA", "a12"};
                
                for(String x: ids) {
                        try {
                                BankAccount ba = new BankAccount(x);
                                Assert.fail(); // If we reached here, it means no exception came.
                        } catch(Exception e) {
                                // we are good here.
                        }
                }
        }
        
        @Test
        public void testBalance() {
                
                String ids[] = new String[] {"123", "A", null, "", "AAAA", "a12"};
                
                for(String x: ids) {
                        try {
                                BankAccount ba = new BankAccount(x);
                                Assert.fail(); // If we reached here, it means no exception came.
                        } catch(Exception e) {
                                // we are good here.
                        }
                }
        }
        
        @Test
        public void testInitialization() {

                try {
                        BankAccount ba = new BankAccount(-2, "A123");
                        Assert.fail(); // If we reached here, it means no exception came.
                } catch(Exception e) {
                        // we are good here.
                }
                
                try {
                        BankAccount ba = new BankAccount(12000, "A123");
                        Assert.fail(); // If we reached here, it means no exception came.
                } catch(Exception e) {
                        // we are good here.
                }
        }
}

class BankAccount {

        private String accountID;
        private double balance;
        
        private void validateId(String accountID) {
                if(accountID == null || accountID.length() != 4 ||
                                !Character.isAlphabetic(accountID.charAt(0)) ||
                                !Character.isDigit(accountID.charAt(1)) ||
                                !Character.isDigit(accountID.charAt(2)) ||
                                !Character.isDigit(accountID.charAt(3))) {
                                throw new IllegalArgumentException("Invalid accountId");
                        }
        }
        /**
         * Constructs a bank account with a zero balance
         * 
         * @param accountID - ID of the Account
         */
        public BankAccount(String accountID) {
                validateId(accountID);
                balance = 0;
                this.accountID = accountID;
        }

        /**
         * Constructs a bank account with a given balance
         * 
         * @param initialBalance the initial balance
         * @param accountID      - ID of the Account
         */
        public BankAccount(double initialBalance, String accountID) {
                validateId(accountID);
                
                if(initialBalance > 10000 || initialBalance < 0) {
                        throw new IllegalArgumentException("Invalid Balance");
                }
                
                this.accountID = accountID;
                balance = initialBalance;
        }

        /**
         * Returns the Account ID
         * 
         * @return the accountID
         */
        public String getAccountID() {
                return accountID;
        }

        /**
         * Sets the Account ID
         * 
         * @param accountID
         */
        public void setAccountID(String accountID) {
                this.accountID = accountID;
        }

        /**
         * Deposits money into the bank account.
         * 
         * @param amount the amount to deposit
         */
        public void deposit(double amount) {
                if(amount > 10000) {
                        throw new IllegalArgumentException("Deposit amount can not be more than 10000");
                }
                balance += amount;
        }

        /**
         * Withdraws money from the bank account.
         * 
         * @param amount the amount to withdraw
         * @return true if allowed to withdraw
         */
        public boolean withdraw(double amount) {
                boolean isAllowed = balance >= amount;
                if (isAllowed)
                        balance -= amount;
                return isAllowed;
        }

        /**
         * Gets the current balance of the bank account.
         * 
         * @return the current balance
         */
        public double getBalance() {
                return balance;
        }

}
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

COMPLETE JAVA CODE public class Point2 { private double x; private double y;    /** *...
COMPLETE JAVA CODE public class Point2 { private double x; private double y;    /** * Create a point with coordinates <code>(0, 0)</code>. */ public Point2() { complete JAVA code this.set(0.0, 0.0); COMPLETE CODE }    /** * Create a point with coordinates <code>(newX, newY)</code>. * * @param newX the x-coordinate of the point * @param newY the y-coordinate of the point */ public Point2(double newX, double newY) { complete Java code this.set(newX, newY); }    /** * Create a...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
Suppose we have a Java class called Person.java public class Person { private String name; private...
Suppose we have a Java class called Person.java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName(){return name;} public int getAge(){return age;} } (a) In the following main method which lines contain reflection calls? import java.lang.reflect.Field; public class TestPerson { public static void main(String args[]) throws Exception { Person person = new Person("Peter", 20); Field field = person.getClass().getDeclaredField("name"); field.setAccessible(true); field.set(person, "Paul"); } }...
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
public class StringNode { private String item; private StringNode next; } public class StringLL { private...
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } } In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position...
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
mport java.util.Scanner; public class BankAccount { //available balance store static double availableBalance; // bills constants final...
mport java.util.Scanner; public class BankAccount { //available balance store static double availableBalance; // bills constants final static int HUNDRED_DOLLAR_BILL = 100; final static int TWENTY_DOLLAR_BILL = 20; final static int TEN_DOLLAR_BILL = 10; final static int FIVE_DOLLAR_BILL = 15; final static int ONE_DOLLAR_BILL = 1; public static void main(String[] args) { System.out.print("Welcome to CS Bank\n"); System.out.print("To open a checking account,please provide us with the following information\n:" ); String fullname; String ssn; String street; String city; int zipCode; Scanner input =...
The following code is included for the java programming problem: public class Bunny {        private...
The following code is included for the java programming problem: public class Bunny {        private int bunnyNum;        public Bunny(int i) {               bunnyNum = i;        }        public void hop() {               System.out.println("Bunny " + bunnyNum + " hops");        } } Create an ArrayList <????> with Bunny as the generic type. Use an index for-loop to build (use .add(….) ) the Bunny ArrayList. From the output below, you need to have 5. Use an index for-loop...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT