Object and JUnit - Arizona Computer Science

Download Report

Transcript Object and JUnit - Arizona Computer Science

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
BankAccount
instance
variables
-String my_ID
-double my_balance
methods
+withdraw(double amount)
+deposit(double amount)
+double getBalance( )
+String getID( )
+String toString()
BankAccount: anAcct
my_ID = "Kim"
my_balance = 100.0
BankAccount: acct2
instance
(object)
state
instance
(object)
my_ID = "Daly"
my_balance = 75.00
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;
construction requires new
class-name identifier = new class-name(initial-value(s));
 object
 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