Chapter 3 Objects and JUnit. Asserting Java Rick Mercer

Similar documents
D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Unit Testing & JUnit

Computer Programming I

CS106A, Stanford Handout #38. Strings and Chars

+ Introduction to JUnit. IT323 Software Engineering II By: Mashael Al-Duwais

Introduction to Java Lecture Notes. Ryan Dougherty

java Features Version April 19, 2013 by Thorsten Kracht

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Chapter 13 - Inheritance

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

JUnit Automated Software Testing Framework. Jeff Offutt. SWE 437 George Mason University Thanks in part to Aynur Abdurazik. What is JUnit?

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Moving from CS 61A Scheme to CS 61B Java

CS193j, Stanford Handout #10 OOP 3

Inheritance, overloading and overriding

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

High-Level Language. Building a Modern Computer From First Principles.

Introduction to Java

D06 PROGRAMMING with JAVA

ICOM 4015: Advanced Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

11 November

Text Processing In Java: Characters and Strings

sveltest: A testing language

LAB 3 Part 1 OBJECTS & CLASSES

Unit Testing JUnit and Clover

Part 1 Foundations of object orientation

7 Mutating Object State

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Eryq (Erik Dorfman) Zeegee Software Inc. A Crash Course in Java 1

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Mutual Exclusion using Monitors

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Unit Testing. and. JUnit

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

CS 111 Classes I 1. Software Organization View to this point:

Writing Self-testing Java Classes with SelfTest

CISC 181 Project 3 Designing Classes for Bank Accounts

SpiraTest / SpiraTeam Automated Unit Testing Integration & User Guide Inflectra Corporation

More on Objects and Classes

Fondamenti di C++ - Cay Horstmann 1

Java CPD (I) Frans Coenen Department of Computer Science

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

A Practical Guide to Test Case Types in Java

Project 4 DB A Simple database program

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Testing, Debugging, and Verification

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Chapter 1 Java Program Design and Development

Java Classes. GEEN163 Introduction to Computer Programming

Pemrograman Dasar. Basic Elements Of Java

5. Advanced Object-Oriented Programming Language-Oriented Programming

CS 1133, LAB 2: FUNCTIONS AND TESTING

Tutorial for Creating Resources in Java - Client

The C Programming Language course syllabus associate level

Lecture 5: Java Fundamentals III

CS 106 Introduction to Computer Science I

Understanding class definitions

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Introduction to Java. CS 3: Computer Programming in Java

Java: overview by example

6.1. Example: A Tip Calculator 6-1

Java Interview Questions and Answers

Quick Introduction to Java

An Introduction to Classes

Week 1: Review of Java Programming Basics

Java Unit testing with JUnit 4.x in Eclipse

Lecture 9. Semantic Analysis Scoping and Symbol Table

Java programming for C/C++ developers

If you wanted multiple screens, there was no way for data to be accumulated or stored

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Programming

Lecture 1 Introduction to Android

Object-Oriented Programming in Java

Iteration CHAPTER 6. Topic Summary

D06 PROGRAMMING with JAVA

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

AP Computer Science Static Methods, Strings, User Input

CS170 Lab 11 Abstract Data Types & Objects

Effective unit testing with JUnit

Introduction to Data Structures

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

J a v a Quiz (Unit 3, Test 0 Practice)

How To Test In Bluej

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Habanero Extreme Scale Software Research Project

Welcome to the AITP NCC 2000 Java Competition in Tampa, Florida.

Building Java Programs

Transcription:

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