object and junit - computer sciencemercer/presentations/03-objects.pdf · a bankaccount type...

25
Asserting Java © Rick Mercer Chapter 3 Objects and JUnit

Upload: others

Post on 20-Jul-2020

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Asserting Java

©Rick Mercer

Chapter 3

Objects and JUnit

Page 2: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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.

Page 3: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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

Page 4: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

A BankAccount type

BankAccount models a simple account at a bank

This class could have a collection of methods to allow for operations like thesewithdraw(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

Page 5: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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);

Page 6: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Class and Object Diagrams

Relationship between a class and it objects Each object stores its state with “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: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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;

}

}

Page 8: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Constructing objects

Whereas primitives may be initialized with one valueint 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);

Page 9: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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

Page 10: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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)

Page 11: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Messages continued

Example Messages

// Construct three objectsBankAccount 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();

Page 12: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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);

Page 13: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Chapter 3: Objects

Asserting Java

©Rick Mercer

JUnit

and the

String Type

Page 14: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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

Page 15: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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);

Page 16: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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);

}

}

Page 17: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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

Page 18: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

Demo Behavior (and test)

Page 19: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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

Page 20: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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 literalString 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

Page 21: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

A 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: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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 char charAt(int index)

Page 23: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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 int indexOf(String subString)

Page 24: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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);

}

public String toUpperCase()

public String toLowerCase()

Page 25: Object and JUnit - Computer Sciencemercer/Presentations/03-Objects.pdf · A BankAccount type BankAccountmodels a simple account at a bank This class could have a collection of methods

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