asserting java ©rick mercer chapter 3 objects and junit

25
Asserting Java Asserting Java © © Rick Mercer Rick Mercer Chapter 3 Chapter 3 Objects and Objects and JUnit JUnit

Upload: jewel-goodwin

Post on 18-Dec-2015

232 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Asserting JavaAsserting Java©©Rick MercerRick Mercer

Chapter 3Chapter 3

Objects and JUnitObjects and JUnit

Page 2: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Find real world entitiesFind 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.

Page 3: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Nouns are possible classesNouns are possible classes

Potential objects to model a solutionPotential objects to model a solution bank teller transaction customers most recent 10 transactions bank account we'll consider this one

window

Page 4: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

A A BankAccount BankAccount type type

BankAccountBankAccount models a simple account at a bankmodels a simple account at a bank This class could have a collection of methods to This class could have a collection of methods to

allow for operations like theseallow for operations like these withdraw(50.00)withdraw(50.00) deposit(152.27)deposit(152.27) getBalance() getBalance() // return account balance// return account balance getID() getID() // return account identification// return account identification

The type allows all instances to have state (values) The type allows all instances to have state (values) such as such as

an ID such as an ID such as "Kim""Kim" or or "085551234""085551234" a balance such as a balance such as 507.99507.99

Page 5: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Constructing objectsConstructing objects

The The BankAccountBankAccount class is not part of Java class is not part of Java It is domain specific, as in for a banking applicationIt is domain specific, as in for a banking application

Construct Construct BankAccountBankAccount objects with two values: objects with two values: A String to initialize the IDA String to initialize the ID A number that represents the current balanceA number that represents the current balance

// Construct BankAccount objects with two argumentsBankAccount anAccount = new BankAccount("Kim", 100.00);BankAccount acct2 = new BankAccount("Daly", 75.00);

Page 6: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Class and Object Diagrams and Object Diagrams

Relationship between a class and it objectsRelationship between a class and it objects Each object stores its state via instance variablesEach object stores its state via instance variables

-String my_ID -double my_balance

+withdraw(double amount) +deposit(double amount) +double getBalance( ) +String getID( ) +String toString()

BankAccount BankAccount: anAcct

my_ID = "Kim" my_balance = 100.0

my_ID = "Daly" my_balance = 75.00

BankAccount: acct2

class name

instance variables

methods

instance (object)

instance (object)

state

state

Page 7: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Preview Chapters 4 and 5Preview Chapters 4 and 5Methods and Data togetherMethods and Data together (object-oriented)(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; } }

Page 8: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Constructing objectsConstructing objects

Whereas primitives may be initialized with one valueWhereas primitives may be initialized with one value int n = 0; int n = 0; double x = 0.000001; double x = 0.000001;

object construction requires object construction requires new new

class-name identifier class-name identifier == newnew class-nameclass-name((initial-value(s)initial-value(s));); Some classes require 0, 1, 2, 3, or more argumentsSome classes require 0, 1, 2, 3, or more arguments

BankAccount myAcct = new BankAccount("Bob", 123.45);

String name = new String("Kim Broderbroens");

JButton aButton = new JButton("A Button");

Font aFont = new Font("Courier", Font.ITALIC, 24);

GregorianCalendar d = new GregorianCalendar(2001, 1, 1);

Page 9: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

What is an Object?What is an Object? Object: a bunch of bits in the computer memoryObject: a bunch of bits in the computer memory Every object hasEvery object has

1) a name used to locate the object 1) a name used to locate the object reference variablereference variable

2) messages it understands2) messages it understands3) values (data) it "remembers" 3) values (data) it "remembers" a.k.a statea.k.a state

The value are often initialized at construction as The value are often initialized at construction as memory is allocated with memory is allocated with new

We send messages (call functions) to objectsWe send messages (call functions) to objects to get something doneto get something done to retrieve remembered valuesto retrieve remembered values

Page 10: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Sending MessagesSending Messages

Each type, implemented as a Java class, has a Each type, implemented as a Java class, has a collection of methods. For examplecollection of methods. For example

BankAccountBankAccount has has withdraw withdraw deposit deposit getID getBalancegetID getBalance

StringString has has length length indexOf indexOf charAt charAt toLowerCasetoLowerCase

A method is invoked via a A method is invoked via a messagemessage A message has a sender (main e.g.), a receiver (the A message has a sender (main e.g.), a receiver (the

object), a object), a message-namemessage-name and the and the argumentsarguments

object name object name .. messsage-namemesssage-name(( arguments arguments))

Page 11: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Messages Messages continuedcontinued

Example MessagesExample Messages

// Construct three objects BankAccount myAcct = new BankAccount("Bob", 123.45); String name = new String("Kim Broderbroens"); JTextField oneLineEditor = new JTextField("Click me");

// Several 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();

Page 12: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

MessagesMessages

Some messages return information about an Some messages return information about an object's stateobject's state

A A messagemessage that asks the object to return information: that asks the object to return information: anAccount.getBalance();anAccount.getBalance();

Other messages tell an object to do somethingOther messages tell an object to do something A A message message that tells the object to do something: that tells the object to do something:

anAccount.withdraw(25.00);anAccount.withdraw(25.00);

Page 13: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Chapter 3: ObjectsChapter 3: ObjectsAsserting JavaAsserting Java©©Rick MercerRick Mercer

JUnit JUnit and the and the String TypeString Type

Page 14: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

JUnitJUnit

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, . . .

JUnit also provides a convenient way to reason and demonstrate how objects work with assertions

Page 15: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

AssertionsAssertions

Assertion: A statement that is expected to be trueAssertion: A statement that is expected to be true if it is not, there is something wrongif it is not, there is something wrong

Junit provides many assertions such as Junit provides many assertions such as assertTrueassertTrue, , assertFalseassertFalse, and , and assertEqualsassertEquals

General Form: A FEW Junit assertionsGeneral Form: A FEW Junit assertions assertEquals(intassertEquals(int expectedexpected,, int int actualactual); ); assertEquals(doubleassertEquals(double expectedexpected,, doubledouble actualactual,, doubledouble errorerror);); assertTrue(assertTrue(BooleanExpressionBooleanExpression); ); assertFalse(assertFalse(BooleanExpressionBooleanExpression); );

Page 16: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Example Unit Test for BankAccountExample 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); } }

Page 17: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Object BehaviorObject Behavior

JUnit allows a coherent way to observe the how JUnit allows a coherent way to observe the how objects workobjects work

The next slide shows several thingsThe next slide shows several things Attempt to withdraw with a negative amount is allowedAttempt to withdraw with a negative amount is allowed

The state of the objects changes The state of the objects changes We'll fix this when we consider the guarded action patternWe'll fix this when we consider the guarded action pattern

Attempt to withdraw more than the balance is allowedAttempt to withdraw more than the balance is allowed The state is changed The state is changed We'll fix this when we consider the guarded action patternWe'll fix this when we consider the guarded action pattern

Page 18: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Demo Behavior (and test)Demo Behavior (and test)

Page 19: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

AssertionsAssertions

Assertions help show the current state of objects Assertions help show the current state of objects and convey the results of messagesand convey the results of messages

Assertions are one way to become familiar with Assertions are one way to become familiar with types such as types such as BankAccountBankAccount and and StringString

The next slides show state of Java's The next slides show state of Java's StringString type type and the return values of and the return values of StringString messages messages

Page 20: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Java's Java's StringString type type

Java has a class for manipulating String objectsJava has a class for manipulating String objects The character set could be almost any in the worldThe character set could be almost any in the world We're using the ASCII character setWe're using the ASCII character set

Construct strings with a string literalConstruct strings with a string literal

String str = new String("with new");String str = new String("with new");

Or let the compiler add Or let the compiler add new for us for us // s2 constructed without new // s2 constructed without new String str2 = "Don't need new";String str2 = "Don't need new";

StringString methods include methods include length charAt substring indexOf length charAt substring indexOf toUpperCase toUpperCase

Page 21: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

A length message returns number of charactersA length message returns number of characters

public int length()

@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()); }

Page 22: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

A A charAtcharAt message returns the character message returns the character located at the index passed as an int argument. located at the index passed as an int argument.

String objects have zero-based indexingString objects have zero-based indexing The first character is located at index 0, the 2nd The first character is located at index 0, the 2nd

character is at index 1character is at index 1 charAt(str.length())charAt(str.length()) causes a runtime errorcauses 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 char charAt(int index)

Page 23: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

An An indexOfindexOf message returns the index where message returns the index where the argument begins in the Stringthe argument begins in the String

If not found, If not found, indexOfindexOf returns -1 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 int indexOf(String subString)

Page 24: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

A A toUpperCasetoUpperCase message returns a new string like the message returns a new string like the original replacing lower case letters with upper case letters original replacing lower case letters with upper case letters

A A toLowerCasetoLowerCase message returns a new string like the message returns a new string like the original replacing lower case letters with upper case lettersoriginal replacing lower case letters with upper case letters

@Testpublic void testToUpperAndToLower() { String str1 = "aBcD"; assertEquals("ABCD", str1.toUpperCase()); assertEquals("abcd", str1.toLowerCase()); // Expected? Hint: the state remains the same assertEquals("____________", str1);}

public String toUpperCase()public String toLowerCase()

Page 25: Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit

Summary: Object and ClassesSummary: Object and Classes

Objects model real world entities that are Objects model real world entities that are more complex than numbers or single more complex than numbers or single characterscharacters

Objects are "constructed" from an existing class such as Objects are "constructed" from an existing class such as StringString or or BankAccountBankAccount

A class is a blueprint for constructing many objectsA class is a blueprint for constructing many objects A class is a collection of related methods and A class is a collection of related methods and

data to serve a single purposedata to serve a single purpose Each object can "remember" (store) its own Each object can "remember" (store) its own

set of valuesset of values 1,000 BankAccounts can have 1,000 unique IDs1,000 BankAccounts can have 1,000 unique IDs