Chapter 3 Objects and JUnit Asserting Java Rick Mercer
Find real world entities The Bank Teller Specification Implement a bank teller application to allow bank customers to access bank accounts through unique identification. A customer, with the help of the teller, may complete any of the following transactions: withdraw money, deposit money, query account balances, and see the most recent 10 transactions. The system must maintain the correct balances for all accounts. The system must be able to process one or more transactions for any number of customers.
Nouns are possible classes Potential objects to model a solution bank teller transaction customers most recent 10 transactions bank account we'll consider this one window
A BankAccount type BankAccount models a simple account at a bank This class could have a collection of methods to allow for operations like these withdraw(50.00) deposit(152.27) getbalance() // return account balance getid() // return account identification The type allows all instances to have state (values) such as an ID such as "Kim" or "085551234" a balance such as 507.99
Constructing objects The BankAccount class is not part of Java It is domain specific, as in for a banking application Construct BankAccount objects with two values: A String to initialize the ID A number that represents the current balance // Construct BankAccount objects with two arguments BankAccount anaccount = new BankAccount("Kim", 100.00); BankAccount acct2 = new BankAccount("Daly", 75.00);
Class and Object Diagrams Relationship between a class and it objects Each object stores its state with instance variables class name instance variables methods BankAccount -String my_id -double my_balance +withdraw(double amount) +deposit(double amount) +double getbalance( ) +String getid( ) +String tostring() BankAccount: anacct my_id = "Kim" my_balance = 100.0 BankAccount: acct2 my_id = "Daly" my_balance = 75.00 instance (object) state instance (object) state
Preview new Types and Java Classes Methods and Data together (object-oriented) public class BankAccount { private String ID; private double balance; public BankAccount(String initid, double initbalance) { ID = initid; balance = initbalance; public String getid() { return ID; public double getbalance() { return balance; public void deposit(double amount) { balance = balance + amount; public void withdraw(double amount) { balance = balance - amount;
Constructing objects Whereas primitives may be initialized with one value int n = 0; double x = 0.000001; object construction requires new class-name identifier = new class-name(initial-value(s)); Some classes require 0, 1, 2, 3, or more arguments BankAccount myacct = new BankAccount("Dakota", 123.45); String name = new String("Kim Baker"); JButton abutton = new JButton("A Button"); Font afont = new Font("Courier", Font.ITALIC, 24); GregorianCalendar epic = new GregorianCalendar(2001, 1, 1);
What is an Object? Object: a bunch of bits in the computer memory Every object has 1) a name used to locate the object reference variable 2) messages it understands 3) values (data) it "remembers" a.k.a state The value are often initialized at construction as memory is allocated with new We send messages (call functions) to objects to get something done to retrieve remembered values
Sending Messages Each type, implemented as a Java class, has a collection of methods. For example BankAccount has withdraw deposit getid getbalance String has length indexof charat tolowercase A method is invoked via a message A message has a sender (main e.g.), a receiver (the object), a message-name and the arguments object name. messsage-name( arguments)
Messages continued Example Messages // Construct three objects BankAccount myacct = new BankAccount("Kim", 123.45); String name = new String("Dakota Baker"); JTextField onelineeditor = new JTextField("Click me"); // Several a few messages (many more possible) myacct.deposit(123.45); myacct.withdraw(20.00); double balance = myacct.getbalance(); name = name.touppercase(); // Change name int spaceposition = name.indexof(" "); String buttontext = onelineeditor.gettext(); onelineeditor.settext("button now has this text"); buttontext = onelineeditor.gettext();
Messages Some messages return information about an object's state A message that asks the object to return information: anaccount.getbalance(); Other messages tell an object to do something A message that tells the object to do something: anaccount.withdraw(25.00);
JUnit and the String Type Chapter 3: Objects Asserting Java Rick Mercer
JUnit JUnit: A framework for designing and testing Java types using classes Can be used standalone, but is part of all Java Development Environments: Eclipse, Dr. Java, BlueJ, NetBeans,... Virtually all programming languages have a similar testing tool: C++Unit, PyUnit, HTTPUnit, JUnit also provides a convenient way to reason and demonstrate how objects work with assertions
Assertions Assertion: A statement that is expected to be true if it is not, there is something wrong Junit provides many assertions such as asserttrue, assertfalse, and assertequals General Form: A few JUnit assertions (may more exist) assertequals(int expected, int actual); assertequals(double expected, double actual, double error); asserttrue(booleanexpression); assertfalse(booleanexpression);
Example Unit Test for BankAccount import static org.junit.assert.*; import org.junit.test; public class BankAccountTest { @Test // This is a test method public void testdeposit() { BankAccount b1 = new BankAccount("Ali", 0.00); assertequals(0.0, b1.getbalance(), 1e-14); b1.deposit(123.45); assertequals(123.45, b1.getbalance(), 1e-14); @Test // Another test method public void testwithdraw() { BankAccount b2 = new BankAccount("Britt", 500.00); b2.withdraw(160.01); assertequals(339.99, b2.getbalance(), 1e-14);
Object Behavior JUnit allows a coherent way to observe the how objects work The next slide shows several things Attempt to withdraw with a negative amount is allowed The state of the objects changes We'll fix this when we consider the guarded action pattern Attempt to withdraw more than the balance is allowed The state is changed We'll fix this when we consider the guarded action pattern
Demo Behavior (and test)
Assertions Assertions help show the current state of objects and convey the results of messages Assertions are one way to become familiar with types such as BankAccount and String The next slides show state of Java's String type and the return values of String messages
Java's String type Java has a class for manipulating String objects The character set could be almost any in the world We're using the ASCII character set Construct strings with a string literal String str = new String("with new"); Or let the compiler add new for us // s2 constructed without new String str2 = "Don't need new"; String methods include length charat substring indexof touppercase
public int length() A length message returns number of characters @Test public void testlength() { String str1 = "abcdef"; String str2 = "012"; // What are the expected values that // makes these assertions pass? assertequals(, str1.length()); assertequals(, str2.length());
public char charat(int index) A charat message returns the character located at the index passed as an int argument. String objects have zero-based indexing The first character is located at index 0, the 2nd character is at index 1 charat(str.length()) causes a runtime error @Test public void testcharat() { String str = "Zero Based"; assertequals('z', str.charat(0)); assertequals('o', str.charat(3)); assertequals(' ', str.charat(4)); assertequals('d', str.charat(9));
public int indexof(string substring) An indexof message returns the index where the argument begins in the String If not found, indexof returns -1 @Test public void testindexof() { String str = "Smiles a lot, lots of smiles"; assertequals(9, str.indexof("lot")); assertequals(1, str.indexof("mile")); assertequals(22, str.indexof("smiles")); assertequals(-1, str.indexof("not here"));
public String touppercase() public String tolowercase() A touppercase message returns a new string like the original replacing lower case letters with upper case letters A tolowercase message returns a new string like the original replacing lower case letters with upper case letters @Test public void testtoupperandtolower() { String str1 = "abcd"; assertequals("abcd", str1.touppercase()); assertequals("abcd", str1.tolowercase()); // Expected? Hint: the state remains the same assertequals(" ", str1);
Summary: Object and Classes Objects model real world entities that are more complex than numbers or single characters Objects are "constructed" from an existing class such as String or BankAccount A class is a blueprint for constructing many objects A class is a collection of related methods and data to serve a single purpose Each object can "remember" (store) its own set of values 1,000 BankAccounts can have 1,000 unique IDs