Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Science I Topic 11: Introduction to OOP with Java: Classes and Object Prof. Dr. Max Mühlhäuser Dr. Guido Rößling.

Similar presentations


Presentation on theme: "Introduction to Computer Science I Topic 11: Introduction to OOP with Java: Classes and Object Prof. Dr. Max Mühlhäuser Dr. Guido Rößling."— Presentation transcript:

1 Introduction to Computer Science I Topic 11: Introduction to OOP with Java: Classes and Object
Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

2 Lecture Outline Object-oriented design in a nutshell; classes and objects in Java Interpreters, compilers, virtual machines; Java compile and runtime environment Visibility of variables in Java Packages Introduction to testing Java classes with Eclipse and JUnit

3 Object-oriented programming (OOP)
OOP: one of the existing programming paradigms Other paradigms: functional programming, logic programming OOP models “the world” as a set of cooperating objects, where: Each object is responsible for a well-defined part of the overall computation Encapsulates the definition of the data needed for this part of the computation and of operations that process this data Can use services of other known objects to perform the computation Each object is an instance of a class Classes are organized in an inheritance hierarchy Class hierarchies correspond to concept hierarchies in the application domain to be modeled

4 Object-Oriented Programming (OOP)
Initial example: writing software for the real estate company Fine&Expensive, which manages and rents exclusive houses Objects will represent houses, employees, and clients For each house, we need to store information about the managing employee, the owner, number of bedrooms, etc. For each client, we need to manage the number of houses (s)he has for rent, the name, phone number, etc. Employees have a name, phone number, list of managed houses, … Different types of houses will be modeled as heirs of a class that captures what all houses have in common One-family house, multifamily residence

5 Object-Oriented Programming (OOP)
employee manager Important The world of Fine&Expensive manages Smith Miller ownedBy Rich

6 Object-Oriented Programming (OOP)
The world of real estate companies Ur_Object Type owns * Person House manages 0..2 responsible for 2..10 Employee Client One-family house Multifamily- residence Manager House- Manager Concepts & Categorization

7 Object-Oriented Programming (OOP)
The world of rental companies Person House A concrete instantiation owns * 0..2 One-family house Multifamily- residence responsible for Employee Client 2..10 Manager House- Manager manages

8 Classes and Constructor Operations
In general, a class describes the common aspects of a group of objects (instances) that share the same set of properties (attributes) the same behavior (operations) Data (Variables) Methods Blueprint (template) for objects; describes their structure and services

9 Classes in Java The definition block of a class consists of
<ClassDefinition> = class Class-Name [extends SuperClassName] <ClassDefinitionBlock> <ClassDefinitionBlock> = { <MemberDefinition> ... <MemberDefinition> } <MemberDefinition> = <FieldDeclaration> | <OperationDefinitons> | <ConstructorDefinitions> The definition block of a class consists of a set of variable declarations also called attributes, instance variables, fields a set of operation definitions constructor definitions

10 Attributes (Instance Variables, Fields)
Attributes are variables that model properties of an object (that is why they are called instance variables) Current value of a counter, current balance of an account… Attribute variables have a name, a type and a value The name is mostly written in lower case Attribute values change during program execution Remember: int is a primitive type in Java. It represents the class of natural numbers between -2,147,483,648  and 2,147,483,647 class Counter { int currentVal; ... } name type class Counter { int currentVal = 10; ... } (define (make-counter) (local ( (define currentVal 10) ... ) value

11 Constructor Operations
Each class defines so-called constructors A constructor defines, by means of its parameters, generic initialization instructions In Java, constructors are special operations that have the same name as the class no return value formal parameter of the constructor class Counter { int currentVal; ... Counter(int initVal) { currentVal = initVal; } attributes are initialized with values of the actual parameters of the constructor call In welcher Position soll der Roboter ursprünglich sein, wie viele Piepser soll er ursprünglich in der Tasche haben ... (define (make-counter initVal) (local ( (define currentVal initVal) ... )

12 Constructor Operations
Initialization instructions are defined in a class once and used multiple times Creation of multiple counter instances of the same type with differently initialized attributes keyword for the creation of object instances ... Counter c1 = new Counter(3); Counter c2 = new Counter(6); ... (define c1 (make-counter 3)) (define c2 (make-counter 6))

13 Visible outside the body of Counter
The Java Class Counter class Counter { int currentVal; public Counter(int initVal) { currentVal = initVal; } /** * Effect: Increases the current value of counter by 1 */ public int inc() { currentVal = currentVal + 1; return currentVal; } * Effect: Decreases the current value of counter by 1 public int dec() { currentVal = currentVal - 1; the current value of the counter public int getCurrentVal() { Visible outside the body of Counter JavaDoc comment. Abbreviated due to lack of space on slide.

14 Classes in Scheme and Java
Scheme classes are modeled by constructor functions (make-XXX) Play at the same time the role of Java constructors Return dispatcher functions: Combine and hide all service functions  the only service visible from the outside is the dispatcher Java provides a special form for class definitions Classes are no first-class values  cannot be passed as parameters or returned from functions A class can have multiple initialization instructions The dispatch mechanism is an implicit language feature the dispatcher is part of the Java semantics and does not need to be programmed (more on dispatching operation calls in the next lecture)

15 Class Interfaces in Scheme and Java
Scheme’s service managers (dispatchers) are interface functions: map symbols to functions of different types The interface of a Java class results from the set of operations that are declared public… All non-public operations are invisible from the outside For now, we say that they can only be called from (public) operations of the same class Not quite true; will reconsider later The concept of an interface as a function that binds symbols to operations with a different contracts remains valid… An address-book is an interface: 'add :: symbol number -> void 'search :: symbol -> number

16 Encapsulation in Java (Information Hiding)
class Counter { int currentVal; ... } The attributes of an object are generally invisible outside a class definition. Their values can be accessed only within the methods implementing the operations in the interface of a type. Non-public operations are also encapsulated. ... Counter c1 = new Counter(2); int current = c1.currentVal; int current = c1.getCurrentVal(); // OK

17 Encapsulation (Information Hiding)
General design idea: the process of hiding details of some program module (e.g., class or function) Powerful idea: reduces the complexity of the application No need to understand the hidden details in order to use some module Reduces coupling between modules Can change hidden implementation details without invalidating clients Module interface as contract We have already seen this design idea data abstraction: hide representation of data type Make-functions hide local definitions of objects

18 Encapsulation and Abstraction
Idea: combining elements to create a larger entity that can be used as a primitive one in the next step, thereby hiding the details of the composition Encapsulation is a mechanism to hide information Term sometimes used in a more general sense As a synonym for information hiding Term sometimes used in a more specific (OO) sense Meaning “data and operations together”

19 Classes as a two-fold abstraction
… describe only those attributes and services of real objects that are relevant for the software to model A class definition ignores irrelevant differences between all possible elements (objects) of a class The class Counter ignores possible differences in the current value of the individual counters of this type

20 Classes & Objects Classes in Java are static descriptions ("on paper", respectively: "in the file")  "blueprints" Objects are run-time entities of a program  values dynamic (are kept in the main memory of the computer during run-time) There might be several objects of a class, each with its own identity and state Can be accessed by means of a name Each object belongs to a class and knows its class A class does not (usually) know its objects

21 Characteristics of an Object

22 Performing Computations
Any computation in an OO program is the result of invoking an operation on a previously created object Note the dot-notation for operation invocation public class CounterConsumer { Counter c1 = new Counter(3); Counter c2 = new Counter(6); public void doSomethingWithCounters() { c1.inc(); c1.dec(); System.out.println(c1.getCurrentVal()); c2.inc(); c2.dec(); System.out.println(c2.getCurrentVal()); } (begin (inc c1) (dec c1)) (getCurrentVal c1) (begin (inc c2) (dec c2)) (getCurrentVal c2)

23 Performing Computations
The task is divided into service instructions Formulated as messages (operation invocations) to objects Each message contains: Name of the receiver object: c1 in the example Name of the service (operation) that the receiver shall execute inc(), dec(), ... The operation must be contained in the receiver's interface Only one message is sent at any point in time If there are multiple objects, they can send messages to each other Delegate substasks to known objects

24 Remember: How Everything Begins...
There is a special method called main which is called automatically when a Java program is run… public class CounterTest { // ... public static void main(String[] args) { CounterConsumer cc = new CounterConsumer(); cc.doSomething (); } CounterTest.java Java Compiler javac CounterTest.java java CounterTest Java Bytecode Interpreter

25 Lecture Outline Object-oriented design in a nutshell; classes and objects in Java Interpreters, compilers, virtual machines; Java compile and runtime environment Visibility of variables in Java Packages Introduction to testing Java classes with Eclipse and JUnit

26 Interpreter We have seen that an interpreter is a program that directly executes another program written in a certain programming language Operation mode of interpreters. Let inpExp be the next expression to be executed in the input program: Perform a syntactic analysis of inpExp Map inpExp to an expression (sequence) outExp in the machine language, or the language of the interpreter itself (meta-circular interpreter) Execute outExp Repeat steps 1 to 3 for the next expression in the input program following inpExp

27 Compiler Program in language A Program in language B compiler
A compiler is a program that translates programs from a source language A to a target language B Program in language A Program in language B compiler execution A  source language B  target language source program P1 target program P2 Semantic correctness: Every program P1 in A corresponds to exactly one program P2 in B The destination program P2 must have the same meaning (semantics) as P1

28 Compiler Rear Admiral Grace Murray Hopper (1906 – 1992)
She invented the compiler, she said, because she was lazy and hoped that "the programmer may return back to being a mathematician." Pioneer Computer Scientist: Perhaps her best-known contribution to computing was the invention of the compiler, the intermediate program that translates English language instructions into the language of the target computer.

29 Stages of Compilation Source code gets chopped into a sequence of terminals (tokens, words) Lexical Analysis Tests if the source code conforms to the syntactical rules of the source language. Organizes terminal symbols in valid sentences. Syntactic Analysis Tests if all names used in the source are declared and then used according to their types. Semantic Analysis Code Generation Target program is generated

30 Traditional Compilation
source program in language A Compiler for language A and processor X processor Y processor Z Executable program (binary code) for Linux Windows MacOS Pascal Smalltalk Java Prolog C++ N Languages M Platforms N*M Compilers

31 Advantages and Disadvantages of Interpreters
Advantage: Good support of the testing/prototyping stage of the program  fast prototyping Changed expressions / declarations of the source code directly executable Retranslation of the program not necessary Disadvantage: executing takes longer If expressions are used k times in the source code (e.g., in loops), they are analysed and dispatched k times For each access of the same variable in different locations in the program, the respective address must be determined over and over again

32 Advantages and Disadvantages of Traditional Compilation
Advantage: Optimal utilization of the processor properties Very fast execution of the compiled programs Disadvantage: A program that is written in a higher-level programming language can theoretically run on every machine after being compiled with the appropriate compiler „The difference between theory and practice is that in theory, there is no difference between theory and practice, but in practice there is.“

33 Drawbacks of Traditional Compilation
The compiled program runs only on one processor type or operating system It must be compiled with a different compiler for each processor type or operating system Windows on PC != Linux on PC Programming languages are often defined in a platform dependent way Specific properties of the machine affect the design of the compiler E.g., the size of registers or memory cells which in turn affect the maximal length of the numbers that can be manipulated Consequence: There are often different dialects of a programming language

34 Virtual Machines (VM) A virtual machine is a program (software) that simulates a hardware processor Programs in a higher programming language (e.g., Java) are compiled into the intermediate language The simulated hardware processor has a set of assembler-like instructions that it understands and a set of software registers The instructions of the intermediate language are often called byte code The VM serves as an interpreter for this assembler-like intermediate language A VM hides the specific properties of a certain processor type  adds a new abstraction layer on top of hardware!

35 Virtual Machines (VM) N Languages M Platforms N + M Compilers Pascal
Linux Smalltalk Virtual Machine Windows Java Prolog MacOS C++

36 Advantages and Disadvantages of VMs
Advantages: compiled programs run on all processor types or OS for which there exists a VM Only one compiler is needed for all processor types or operating systems The higher-level language becomes independent of different hardware platforms or OS Of course, you need one VM per processor and OS Disadvantages: byte-code programs are slower than machine programs Solution: just-in-time-compiler compiles byte-code to an executable program for a specific processor type / OS When the code is loaded or the first time the instructions are executed

37 Java Compilation und Runtime Environment
Wichtige Festlegungen der JVM-Spezifikation Befehlsatz, Registerarchitektur Struktur einer class-Datei (auch Class File Format genannt) Stack, Garbage-collected heap, Speicher-Layout Bei der Implementierung der JVM für eine Hardware-/ Betriebssystemarchitektur müssen bestimmte Java-APIs auf die vorhandene System-Call-Schnittstelle abgebildet werden Datei- und Netzwerkzugriffe, GUI

38 Structure of a Java Program
A Java program consists of an arbitrary number of classes, at least one of which must contain the main operation Responsibility of the main operation: Object creation  the construction of an initial minimal set of objects Calling the first operation In general, it should not contain further control flow of the Java program The real control flow is encapsulated within the implementation of the operations of cooperating objects Remember that computations are organized by multiple cooperating objects, and each object covers only a small sub-task The main operation will be started and executed by means of the Java interpreter args ist eine Tabelle mit Zeichenketten und wird benutzt um dem Programm beim Start Parameter zu übergeben Eingabeparameter stehen zunächst nur als Zeichenketten zur Verfügung Möchte man eine Zahl übergeben, so muss die entsprechende Zeichenkette (programmintern) in eine Zahl (z.B. vom Typ int) konvertiert werden  mehr dazu später Statt args kann ein beliebiger Name benutzt werden, die Verwendung von args ist aber üblich

39 Java Runtime Environment
Java Interpreter: program for executing Java byte codes on a particular machine Just-In-Time Compiler (JIT-Compiler) : After being loaded, a class can (optimally) be directly translated into the machine code of the particular machine If the Java installation at hand does not have a JIT compiler, the byte code will be directly executed by the Java interpreter Runtime System: provides important resources to Java program  irrelevant to this course Byte code-Verifier: verifies that the loaded byte codes satisfy the JVM specification Classes can be loaded from the Internet or from the local file system at the runtime of a Java application Part of the security provisions are performed by the verifier

40 Java Compilation (Repeated)
Java compiler Input: Java source file, SomeFile.java, that contains one or more class definitions Such a file is called compilation unit Output: for each class Cl in SomeFile.java, the compiler will generate exactly one file Cl.class that contains the bytecode for the class Cl SomeFile.java Cl1.class class Cl1 {...} class Cl2 {...} class Cl3 {...} Cl2.class Java Compiler Cl3.class

41 Lecture Outline Object-oriented design in a nutshell; classes and objects in Java Interpreters, compilers, virtual machines; Java compile and runtime environment Visibility of variables in Java Packages Introduction to testing Java classes with Eclipse and JUnit

42 Variable Visibility within a Java Class
As in Scheme, a name may be used multiple times for different purposes, e.g., as an instance variable, a parameter, a local variable Similar to Scheme, Java employs lexical scoping: inner declarations have precedence over outer declarations Outer declarations are not directly accessible anymore Using this.<attribute name> one may still access instance variables Local variables and parameters may not be re-declared A re-declaration does not affect the existence of the outer variable Invisibility does not imply non-existence; outside the re-declaring block, the outer variable is visible again

43 Variable Visibility within a Java Class
class Example { int i; char c; void g(int n) { int i, j; for (char c... ) { int k; … i … k … c … n … this.i … } … c …

44 Lecture Outline Object-oriented design in a nutshell; classes and objects in Java Interpreters, compilers, virtual machines; Java compile and runtime environment Visibility of variables in Java Packages Introduction to testing Java classes with Eclipse and JUnit

45 Packages Packages bundle up classes which belong together with respect to an area of responsibility Help to avoid name conflicts Class names have to be unique (but only within a package) Two or more classes may use the same (non-public) class name, e.g., List Hide classes which only serve an internal purpose and should not be visible from outside

46 Package Hierarchies Packages are organized hierarchically
A package may contain other packages Which in turn can contain packages, etc. “Dot” notation for package names package.subpackage.subsubpackage.Class The preamble of a .java file determines with which package the following classes are associated

47 Package Naming Conventions
Package name mirrors the Internet domain name of the manufacturer in reverse order Slashes and “-” are not allowed Replace a dash by an underscore (or skip it) SUN domain: sun.com SUN class: com.sun.p1.p2.X TUD domain: informatik.tu-darmstadt.de TUD class: de.tu_darmstadt.informatik.p1.X This convention helps to ensure world-wide unique class names

48 Package Declaration The same package name may be used in several files
One package may contain several files Faster (re-)compilation supports workload distribution in larger projects The full name of a class always includes the package name (packagename.classname) Shortcut denotation using the class name only is possible within the same package or when the respective package or class has been imported

49 Structure of a Java file
<Source-File> ::= <Package-Declaration> <Import-Declarations> <Type-Definitions> <Package-Declaration> ::= package <Package-name> ; | ε <Package-Name> ::= <Identifier> {. <Package-Name>} Only comments or blank lines may be put before package declarations Only one package name per file Without a package declaration, the contained classes are associated with an anonymous default package

50 Package Import <Import-Declarations> ::= { <Import-Declaration> | ε <Import-Declaration> ::= import <Package-Name> "." (<Class-Name> | "*") ";" Class definitions following the import statement may then access the imported class(es) without specifying the full name If "*" (wild card) is used, all classes contained in the package may be accessed If you only want to import class methods (static), use this notation: import static <Package-Name>.<Class-Name>.<Methode>;

51 Using Packages Using full qualification
java.util.Random numberGenerator = new java.util.Random(); Using import import java.util.Random; ... Random numberGenerator = new Random();

52 Package Import Importing classes with the same name yields a name conflict import java.awt.*; // contains class List import java.util.*; // contains class List // ... java.util.List list; // use package name // to pick one out Two packages are automatically imported the current package the predefined package java.lang containing basic classes such as Object, String, etc.

53 Package Import The Java library contains a number of predefined packages (all part of the JDK) java.applet applet support java.io input/output, files java.net network support java.util utility types, e.g., container types java.util.zip support for .zip archives etc.

54 Package Naming Package names and directory structures Example
The location of the files defining a package mirrors the hierarchical package structure Dots need to be replaced with UNIX  Slash “/” Windows  Backslash “\” Example package name: kilian.hobby.raytracer corresponding UNIX directory structure: kilian/hobby/raytracer

55 Binding Packages Packages and the "CLASSPATH"
A package name is interpreted as a relative path The environment variable CLASSPATH contains all directories which are to be searched for classes or packages Alternatively, a CLASSPATH may also contain ZIP- or JAR-archives, containing classes Example for UNIX CLASSPATH=.:/home/joe/classes:/usr/classes.zip current directory separates directories

56 Binding Packages Packages and the "CLASSPATH"
The directories specified in the CLASSPATH are used as starting points for the relative package name (used as pathnames) Searching order is from left to right It is possible that one package name exists in two or more existing directories Not a good idea, as the selection of a package then depends on the order of the paths in CLASSPATH

57 Lecture Outline Object-oriented design in a nutshell; classes and objects in Java Interpreters, compilers, virtual machines; Java compile and runtime environment Visibility of variables in Java Packages Introduction to testing Java classes with Eclipse and JUnit

58 Testing with JUnit and Eclipse
Test-first programming  Our design recipes require that we write tests before we start coding JUnit is a program (framework) that automates parts of the process of writing and running tests JUnit is already integrated into Eclipse Poor kid, we should have told him to test, then code when he started

59 Motivation: JUnit Similarly to our test cases for Scheme, we also want to be able to test our Java programs We write testing program code that uses sample data on operations and evaluates the result. The testing program is developed and executed in parallel at development time with the actual program Whenever we want to know if certain test cases still work correct We use a testing framework, here JUnit: - for automated unit tests

60 Annotations Before we look at JUnit, let us take a look at annotations
The latest version of JUnit is implemented with annotations Annotations give metadata about code Java 1.5+ defines seven annotations It is possible to add user-defined annotations There are three “real” annotations… …and four “meta” annotations Annotations are marked in code For Annotations refer to the following element Element = line of code, method, …

61 “Real” Annotations @Override @Deprecated @SuppressWarnings
Indicates that a method overrides a method in the base class Can be used to check for typos or errors in method signature @Deprecated Produces a compiler warning if the element is used @SuppressWarnings Turn off compiler warnings for the following element

62 Meta Annotations @Target(arg) @Retention(arg) @Documented @Inherited
Where can the annotation be used? Additional argument: CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE @Retention(arg) How long to keep annotation info? SOURCE = Discarded by compiler CLASS = Available in class-file, discarded at runtime RUNTIME = Retained by virtual machine for run-time use @Documented Include annotation in JavaDoc @Inherited Allow subclasses to inherit annotation

63 Annotations: Example can be used to define new annotations New annotations are defined like interfaces and re-use the (with prefix!) Example: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) UseCase { public int id(); public String description() default "no description"; }

64 Annotations: Example Using previous annotations to define use cases
public class PasswordUtils { @UseCase(id = 47, description = "Password must have one number") public boolean validatePassword() { // validation code... } @UseCase(id = 48) public String encryptPassword() { // encryption code...

65 Annotations and JUnit The latest version of JUnit is based on annotations Test cases are marked with Earlier versions relied on specific naming conventions for test classes; not needed anymore We will come back to JUnit in a moment… But first, a few more words about testing

66 Test stages Client wishes Acceptance Tests Requirements System tests
Development stages with corresponding Tests Client wishes Acceptance Tests Requirements System tests Design Integration tests Code Unit tests X Y A happens before B A B X finds faults in Y

67 Test stages In different stages, different test strategies are useful
Unit Test: Test of code components, e.g. code of a method or a class  structural testing Integration test: Test of the integration of multiple code components  structural testing System test: Test of the whole system against the specification  functional testing Acceptance test: Test of the whole system with real data from the client

68 Testing & Development Methodologies
An unwanted vicious circle… time pressure more time pressure more errors less tests

69 Testing & Development Methodologies: “Agile” Methodologies
code a little test a little Development & testing as interleaved activities Test case creation before code is written Tool support required

70 Testing Testing is a necessity in real life
The earlier faults are found, the better (and cheaper) Development usually is an iterative process with feedback loops If possible, do not only test for quality, but build for quality Systematic Procedures  Software Engineering

71 Testing with Junit 4.4 In the following, we will test a small calculator The implementation of this class is rather easy It will only work for int values It is very simple and inefficient It also has a couple of bugs We will see how JUnit can help us track those bugs!

72 The Calculator Class (Part I)
package calc; public class Calculator { private static int result; // Static variable where the result is stored public void add(int n) { result = result + n; } public void substract(int n) { result = result - 1; //Bug : should be result = result - n public void multiply(int n) { // not ready yet public void divide(int n) { result = result / n; public void square(int n) { result = n * n;

73 The Calculator Class (Part II)
public void squareRoot(int n) { // will be implemented later… for (; ;) ; // Bug : loops indefinitely } public void clear() { // Clears the result result = 0; public void switchOn() { // Switch on the screen, display "hello", beep // and do other things that calculator do nowadays public void switchOff() { // Display "bye bye", beep, switch off the screen public int getResult() { return result;

74 How Do We Test A Calculator?
We want to test each operation separately Add Substract Divide Multiply Square Root – deferred for now (indefinite loop!) We write one test method per test The methods go into a separate class CalculatorTest Tests are annotated before the “public” We need to initialize the calculator before each test Need to send “clear()” to ensure the value is 0 Otherwise, we get incorrect follow-up errors

75 The CalculatorTest Class (Part I)
Choose any package name here package junit4demo; import calc.Calculator; import junit.framework.JUnit4TestAdapter; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * Basic test annotation * as well as assert keyword and assertEqual methods */ public class CalculatorTest { private static Calculator calculator = new Calculator(); // Used for backward compatibility (IDEs, Ant and JUnit 3 text runner) public static junit.framework.Test suite() { return new JUnit4TestAdapter(CalculatorTest.class); } This is our calculator code Several needed imports for JUnit Import only this static method from class Assert Needed for older environments

76 The Calculator Test Class (Part II)
@Before // must be public not protected like the setup public void clearCalculator() { calculator.clear(); } //================================== // Test public void add() { calculator.add(1); assertEquals(calculator.getResult(), 2); @Before: run before each test, so calculator starts each test with value 0 @Test: this is a test method that should be run. This will assert that 1+1 = 2.

77 The Calculator Test Class (Part III)
public void subtract() { calculator.add(10); calculator.substract(2); assertEquals(calculator.getResult(), 8); } public void divide() { calculator.add(8); calculator.divide(2); assertEquals(calculator.getResult(), 5); – deactivated, as it will cause an error (division by 0); more in T16 public void divideByZero() { calculator.divide(0); This will assert that 10-2 = 8 (will fail due to bug) This shall assert that 8/2=5 (will fail, as this is incorrect!) Dividing by 0 must lead to an expected error, else test fails

78 The Calculator Test Class (Part IV)
has a String parameter which displays ready yet") public void multiply() { calculator.add(10); calculator.multiply(10); assertEquals(calculator.getResult(), 100); } Ignore testing multiply, as the implementation is not ready yet. Copy the classes from the course web page Make sure that JUnit 4.4 is installed and added to your project as an “External JAR” Select the class CalculatorTest and choose Run As  JUnit Test The output is shown on the next slide

79 JUnit in Eclipse: Assert Methods etc.

80 JUnit in Eclipse: Run as test case

81 Error Output from JUnit
Brief test results Log of tests run 10-2=8 failed

82 More Advanced Tests We have not used the divideByZero test method
If we do so, we get an (expected) error message! How we can test for the presence of expected errors will be covered together with error treatment in T16. We have not tested the squareRoot method so far Would not be a good idea, since this loops indefinitely! We also should do a general set-up once Create and switch on the calculator before tests are run Switch it off once all tests are finished and set to null The following code takes a closer look achieving this Slightly simplified from the code on the web page

83 Advanced Testing: General Set-Up
package junit4demo; import calc.Calculator; import junit.framework.JUnit4TestAdapter; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * This test uses advanced fixture and timeout */ public class AdvancedTest { private static Calculator calculator; // Used for backward compatibility (IDEs, Ant and JUnit 3 text runner) public static junit.framework.Test suite() { return new JUnit4TestAdapter(AdvancedTest.class); } Make external class visible (T15) Run once when all tests are finished Run before each test Run once before any test is started

84 Test Initialization and Finishing
@BeforeClass // must be public and static public static void switchOnCalculator() { System.out.println("\tSwitch on calculator"); calculator = new Calculator(); calculator.switchOn(); // must be public public static void switchOffCalculator() { System.out.println("\tSwitch off calculator"); calculator.switchOff(); calculator = null; Run once before testing starts: create and switch on the calculator Run once after all tests are completed: switch off calculator and reset attribute to null

85 Tests with Timeout //================================== //= Test = 1000) public void squareRoot() { calculator.squareRoot(2); public void square2() { calculator.square(2); assertEquals(4, calculator.getResult()); // two more tests skipped If not done within 1000ms, this test will fail (needed for indefinite loop!) Tests for the squares of 4 & 5

86 Test Output with Timeout
Test for squareRoot failed due to time out

87 More on JUnit... JUnit can do far more than shown here
However, this is beyond the scope of this lecture Please take a look at the documentation Included JavaDoc for JUnit Good Reference (and base for these slides): Antonio Goncalves, Get Acquainted with the New Advanced Features of JUnit 4


Download ppt "Introduction to Computer Science I Topic 11: Introduction to OOP with Java: Classes and Object Prof. Dr. Max Mühlhäuser Dr. Guido Rößling."

Similar presentations


Ads by Google