0% found this document useful (0 votes)
32 views

Chapter03 - Version Control

This document discusses version control, which allows software teams to work collaboratively by managing changes to files over time. It describes two main approaches: lock-modify-unlock, which only allows one person to edit a file at a time, and copy-modify-merge, which allows concurrent editing by having users make changes to their local copies and then merging those changes. Modern version control systems like Subversion use the copy-modify-merge approach to enable parallel development while preventing data loss from conflicting changes. The document outlines some key features and benefits of version control systems for software development.

Uploaded by

tesfanesh 65tg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Chapter03 - Version Control

This document discusses version control, which allows software teams to work collaboratively by managing changes to files over time. It describes two main approaches: lock-modify-unlock, which only allows one person to edit a file at a time, and copy-modify-merge, which allows concurrent editing by having users make changes to their local copies and then merging those changes. Modern version control systems like Subversion use the copy-modify-merge approach to enable parallel development while preventing data loss from conflicting changes. The document outlines some key features and benefits of version control systems for software development.

Uploaded by

tesfanesh 65tg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Software Engineering Tools and Practices

(SE 4091)

Chapter 03
Version Control

Dileep Kumar G. 1
Chapter Outline
 Introduction to Version Control

 Version Control Configuration and Use

 Cloning an existing repository

 Building JAR files

 Automated build tools: ANT

 Unit Testing using JUnit

SE 4091 2
Dileep Kumar G.
The stages of developing a
software application
 Requirements Analysis
 High-level Design
 Low-level Design
 Implementation
 Integration
 Deploy (SDL)
 Maintain (SDL)

Dileep Kumar G.
3
In many cases, multiple projects
run concurrently

New features are typically


being added to the next
version

While at the same time,


defects need to be
corrected in existing
releases

You will do this more in SDL

SE 4091 4
Dileep Kumar G.
On a single project, a team of
software engineers work together
toward a release

All team members work on the


same code and develop their
respective parts

An engineer may be
responsible for an entire class

Or just a few methods within a


particular class
Dileep Kumar G.
5
Files have to be shared among
developers on a team project

Shared files can be kept in


some type of Repository
where they can be
accessed and worked on by
multiple individuals

Harry and Sally get their own respective


local Working Copies of the Master File in
the Repository

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


6
What might you use for a
Repository?
Would any of these work?

 USB/SD drive

 Private network drive


 E.g. shared “X:” drive

 Cloud drive
 Google drive
 Dropbox
 iCloud

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


7
Sharing files can lead to big
problems…

Adds some method Modifies some other method

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


8
The problem to avoid:

Harry’s changes are still held locally…

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


9
Harry’s changes are lost

‘’

Harry’s local file gets overwritten with


Sally’s latest changes.

‘’

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


10
The Issue: Effective management of
software artifacts, especially code
Some acronyms:
 SCM – Source Code Management

 SCCM – Source Code Configuration


Management
 RCS – Revision Control System

 VCS – Version Control System

 DVCS - Distributed Version Control Systems

Dileep Kumar G.
11
Revision/Version History might help
 …but USB/SD, private network drives do not
maintain revision history

 Cloud drives (e.g. Google Drive, Dropbox,


iCould/Time Machine) maintain a (limited)
history of the various revisions of a file
 Google Drive: keeps last 100 revisions or last 30
days
 Supported in “Classic” mode only – going
away?

 IF you detect a collision, you can manually


merge the differences and resynchronize your
work
 Might be workable for two people – what about 5
or 10?
Dileep Kumar G.
12
Any other disadvantages to
Google Drive/Dropbox/iCloud
 Security?
 Support (bug fixes and new features)?
 Ownership of stored information?
 Cost?
 Ease of Use?
 Acceptance?

Dileep Kumar G.
13
Special-purpose Revision Control
Systems have been around a lot
longer than Google Drive or Dropbox
 SCCS, 1972 (IBM)
 RCS, 1982 (Unix)
 SourceSafe 1995 (Microsoft)
 CVS, 1986 (multi-platform)
 SVN, 2000 (multi-platform)
 Git and Mercurial, 2005 (multi-platform)

The way these work has evolved over the


years
Dileep Kumar G.
14
Features of version control
systems
 All changes to a file are tracked
 Version histories show who, what, when

 Changes can be reverted (rewound to any


earlier version)

 Changes between revisions are easy to


identify

Dileep Kumar G.
15
The Lock-Modify-Unlock
solution Early systems followed this model
(RCS, SourceSafe)

Sally must wait until Harry releases the lock,


although she can retrieve a “readonly”
version of the file in the meantime.
Image: http://svnbook.red-bean.com/ Dileep Kumar G.
16
Lock-Modify-Unlock only allows a
single user to edit the file at a time

Sally must continually poll the system to


see if the file has been unlocked, or Harry
needs to tell her when he unlocks it.

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


17
Lock-Modify-Unlock has
certain drawbacks:
Harry has to remember to release his lock
before Sally (or anyone else) can acquire the
lock in order to edit

Sally has to wait for Harry to finish before


editing (editing must be done sequentially)
 Harry might be adding some new methods (takes
a long time)
 Harry might forget to release the lock before going
home (or on vacation!)
Dileep Kumar G.
18
The Copy-Modify-Merge solution
allows concurrent editing

CVS, SVN use this model

Harry adds Sally adds


new methods comments

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


19
The Repository recognizes
conflicts

Harry is prevented from writing

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


20
Conflicting versions of the files are
merged

Conflicts are automatically


resolved in many cases using
robust merging algorithms.

However, manual merging is


sometimes necessary and can
introduce errors.

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


21
The Repository keeps both
users synchronized

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


22
Copy-Modify-Merge is generally
easy to use and manage

Users can work in parallel

Most of the time, concurrent changes


don’t overlap
 People generally don’t edit exactly the
same code simultaneously, so merging is
done automatically in many cases
 Amount of time spent resolving conflicts is
nearly always less than the time that would
be spent waiting for a lock to be released
Dileep Kumar G.
23
Is Lock-Modify-Unlock ever
needed anymore?
When two or more people need to
work on the same file, the
simultaneous changes may not
be mergable in all cases:
 MS Office documents

 Image documents

 Other binary files

Dileep Kumar G.
24
Subversion is an open-source version
control system that is available and
still supported for many platforms
 Windows
 Mac
 Linux

Many current open-source projects use


Subversion to maintain source code control
 http://subversion.tigris.org/
 Latest release 8/2014

Dileep Kumar G.
25
Subversion’s main drawback is the
centralized nature of the Repository

A repository is typically hosted


on a server.

 Version history is on the


server, not on your local PC
 If the server or network
become unavailable,
everyone gets stuck with the
working copy they have.

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


26
Distributed Version Control
A “remote master” repository is
typically hosted on a server.
 Clones of the remote repository are
maintained on each user’s
computer
 If the server goes down, users can
continue sharing code (provided
they can connect over a network)
by synch’ing to each others’
repositories
 If the network is unavailable, users
can continue reading & writing to
their own local repository –
synch’ing with others later Git and Mercurial use this
Dileep Kumar G. model
Image: http://git-scm.com/book/
27
Merging in a DVCS, part 1

1. Initially, both users’ repositories


2. Both users edit the same file, and their
are synch’d to the remote master;
local repositories reflect their changes
All files are identical.
Dileep Kumar G.
28
Merging in a DVCS, part 2

4. User B attempts to “push” his repository


3. User A “pushes” her repository to the remote to synch; this fails due to
to the remote master to synch; this User A’s earlier push. Remote does
succeeds. not change. 29
Merging in a DVCS, part 3

5. User B “pulls” User A’s updates 6. User B “pushes” his repository


from the remote master, merging to the remote to synch; this now succeeds
A and B together. Merging is
Dileep Kumar G.
automatic with some exceptions.
30
Merging in a DVCS, part 4

7. User B “pulls” from the remote, and everyone is in synch again.

Dileep Kumar G.
31
Repositories can also manage and
track differences between parallel
revisions of a document

 Typically, a software product will undergo


parallel development on different branches (e.g.
for new/future features) while primary
development takes place on the main (master)
branch

Image: http://svnbook.red-bean.com/ Dileep Kumar G.


32
Git takes snapshots

Dileep Kumar G.
33
Git uses checksums
 Git generates a unique SHA-1 hash – 40
character string of hex digits, for every
commit.
 Often we only see the first 7 characters:
1677b2d Edited first line of readme
258efa7 Added line to readme
0e52da7 Initial commit

Dileep Kumar G.
34
A Local Git project has three
areas

Unmodified/modified Staged Committed


Files Files Files

Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.
35
Git file lifecycle

Dileep Kumar G.
36
Basic Workflow
Basic Git workflow:
1. Modify files in your working directory.

2. Stage files, adding snapshots of them to your


staging area.
3. Do a commit, which takes the files as they are
in the staging area and stores that snapshot
permanently to your Git directory.
 Notes:
 If a particular version of a file is in the git directory, it’s considered
committed.
 If it’s modified but has been added to the staging area, it is staged.
 If it was changed since it was checked out but has not been staged, it is
modified. 37
Aside: So what is github?
 GitHub.com is a site for online storage of Git repositories.
 Many open source projects use it, such as the Linux
kernel.
 You can get free space for open source projects or you can
pay for private projects.

Question: Do I have to use github to use Git?


Answer: No!
 you can use Git completely locally for your own purposes, or
 you or someone else could set up a server to share files, or
 you could share a repo with users on the same file system, (as long
everyone has the needed file permissions).
Dileep Kumar G.
38
Get ready to use Git!
1. Set the name and email for Git to use when you commit:
$ git config --global user.name “Bugs Bunny”
$ git config --global user.email bugs@gmail.com

 You can call git config --list to verify these are set.
 These will be set globally for all Git projects you work
with.
 You can also set variables on a project-only basis by not
using the
--global flag.
 You can also set the editor that is used for writing commit
messages:
$ git config --global core.editor emacs (it is vim by
default) 39
Create a local copy of a repo
2. Two common scenarios: (only do one of these)
a) To clone an already existing repo to your current directory:
$ git clone <url> [local-dir-name]
This will create a directory named local-dir-name, containing a
working copy of the files from the repo, and a .git directory
(used to hold the staging area and your actual repo)

b) To create a Git repo in your current directory:


$ git init
This will create a .git directory in your current directory.
Then you can commit files in that directory into the repo:
$ git add file1.java
$ git commit –m “initial project version”

Dileep Kumar G.
40
Git commands
command description
git clone url [dir] copy a git repository so you can add to it
git add files adds file contents to the staging area
git commit records a snapshot of the staging area
git status view the status of your files in the working
directory and staging area
git diff shows diff of what is staged and what is
modified but unstaged
git help [command] get help info about a particular command
git pull fetch from a remote repo and try to merge
into the current branch
git push push your new branches and data to a
remote repository
others: init, reset, branch, checkout, merge, log, tag

Dileep Kumar G.
41
Init a repository
zachary@zachary-desktop:~/code/gitdemo$ git init
Initialized empty Git repository in /home/zachary/code/gitdemo/.git/

zachary@zachary-desktop:~/code/gitdemo$ ls -l .git/
total 32
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 branches
-rw-r--r-- 1 zachary zachary 92 2011-08-28 14:51 config
-rw-r--r-- 1 zachary zachary 73 2011-08-28 14:51 description
-rw-r--r-- 1 zachary zachary 23 2011-08-28 14:51 HEAD
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 hooks
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 info
drwxr-xr-x 4 zachary zachary 4096 2011-08-28 14:51 objects
drwxr-xr-x 4 zachary zachary 4096 2011-08-28 14:51 refs

Dileep Kumar G.
42
Stage the Changes
zachary@zachary-desktop:~/code/gitdemo$ git status
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: hello.txt
#
no changes added to commit (use "git add" and/or "git commit -a")

Dileep Kumar G.
43
Review Changes
zachary@zachary-desktop:~/code/gitdemo$ git add hello.txt
zachary@zachary-desktop:~/code/gitdemo$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: hello.txt
#

Dileep Kumar G.
44
Committing files
 The first time we ask a file to be tracked, and every time
before we commit a file we must add it to the staging area:
$ git add README.txt hello.java
This takes a snapshot of these files at this point in time and adds
it to the staging area.

 To move staged changes into the repo we commit:


$ git commit –m “Fixing bug #22”

Note: To unstage a change on a file before you have committed it:


$ git reset HEAD - filename
Note: To unmodify a modified file:
$ git checkout - filename

Note: These commands are just acting on your local version of repo. 45
Status and Diff
 To view the status of your files in the working directory
and staging area:
$ git status or
$ git status –s
(-s shows a short one line version similar to svn)

 To see what is modified but unstaged:


$ git diff

 To see staged changes:


$ git diff -cached

Dileep Kumar G.
46
Viewing logs
To see a log of all changes in your local repo:
 $ git log or

 $ git log -oneline (to show a shorter version)


1677b2d Edited first line of readme
258efa7 Added line to readme
0e52da7 Initial commit
 git log -5 (to show only the 5 most recent updates, etc.)

Note: changes will be listed by commitID #, (SHA-1 hash)


Note: changes made to the remote repo before the last time you
cloned/pulled from it will also be included here

Dileep Kumar G.
47
Pulling and Pushing
Good practice:
1. Add and Commit your changes to your local repo
2. Pull from remote repo to get most recent changes (fix conflicts if
necessary, add and commit them to your local repo)
3. Push your changes to the remote repo
To fetch the most recent updates from the remote repo into your local repo,
and put them into your working directory:
$ git pull origin master
To push your changes from your local repo to the remote repo:
$ git push origin master
Notes: origin = an alias for the URL you cloned from
master = the remote branch you are pulling from/pushing to,
(the local branch you are pulling to/pushing from is your current branch)
Note: On attu you will get a Gtk-warning, you can ignore this.

Dileep Kumar G.
48
Branching
 To create a branch called experimental:
$ git branch experimental

 To list all branches: (* shows which one you are currently on)
$ git branch

 To switch to the experimental branch:


$ git checkout experimental

 Later on, changes between the two branches differ, to


merge changes from experimental into the master:
$ git checkout master
$ git merge experimental

Note: git log --graph can be useful for showing branches.


Note: These branches are in your local repo!
Dileep Kumar G.
49
Do This:
1. $ git config --global user.name “Your Name”
2. $ git config --global user.email youremail@whatever.com

3. $ git clone https://github.com/rea2000/santalist.git

Then try:
1. $ git log, $ git log --oneline

2. Create a file named userID.txt (e.g. rea.txt)

3. $ git status, $ git status –s

4. Add the file: $ git add userID.txt

5. $ git status, $ git status –s

6. Commit the file to your local repo:


$ git commit –m “added rea.txt file”
7. $ git status, $ git status –s, $ git log --oneline
*WAIT, DO NOT GO ON TO THE NEXT STEPS UNTIL YOU ARE TOLD TO!!
1. Pull from remote repo: $git pull origin master
2. Push to remote repo: $git push origin master
50
Git Resources
 At the command line: (where verb = config, add, commit,
etc.)
$ git help <verb>
$ git <verb> --help
$ man git-<verb>
 Free on-line book: http://git-scm.com/book
 Git tutorial: http://schacon.github.com/git/gittutorial.html
 Reference page for Git: http://gitref.org/index.html
 Git website: http://git-scm.com/
 Git for Computer Scientists (http://eagain.net/articles/git-
for-computer-scientists/)
Dileep Kumar G.
51
Deploying Java applications as
JAR files

How to package an application so


that you can run it outside of Eclipse.

Dileep Kumar G.
52
Consider an Eclipse project

This application consists of files in two directories, in


packages called demo.app and demo.data
Dileep Kumar G.
53
When you run an application from within Eclipse,
it (internally) issues the following command:
java –cp “D:\My Docs\se4091\JARDemo\bin”
demo.app/JARDemoApp

java is the command that runs the Java Virtual Machine


 Found at C:\Program Files\Java\jdk1.6.0_03\bin\java.exe

JARDemoApp is the name of the main class

demo.app is the package containing the main class


(demo.data is the name of the package containing the MyData class)

-cp <classpath> specifies the base directory where the .class file(s) for
the packages are located
 Not including the package subdirectories

Dileep Kumar G.
54
If your class files are in multiple file folders, you
must include them all:
java –cp “D:\My Docs\se4091\JARDemo\bin;
D:\MyDocs\Documents\ASTU\Courses\Example
Programs\se4091\UIHelper\bin” demo.app/JARDemoApp

-cp <classpath> specifies ALL base directories where the .class file(s)
for the packages are located
 Note that each directory is separated by a semicolon
 With NO space between directories

Dileep Kumar G.
55
A Java Archive (JAR) file enables you
to bundle multiple files into a single
archive file
A JAR file is essentially a ZIP file with specific
contents:
 The files you want to zip into the file
 .class files
 Source files (.java) if you want to enable debugging
 Javadoc files if you want to provide context-sensitive
help for the classes in the JAR file
 A manifest file (MANIFEST.MF)
 Which specifies what’s in the JAR file

Dileep Kumar G.
56
The jar utility can be used to
create JAR files
jar cfm <jarfile> <manifest> -C <bin>
<classfiles>
jar is the command that runs the jar utility
 Same as C:\Program Files\Java\jdk1.6.0_03\bin\jar.exe

jarfile is the name of the JAR file you want to create

manifest is the name of a file containing manifest information


Note : The contents of the manifest must be encoded in ansi.
-C <bin> specifies the location of the classfiles

classfiles specifies the files you want to place in the JAR file
 Separated by spaces
 Must include the full package folder path

Dileep Kumar G.
57
To bundle files in the same
directory into a JAR file:
jar cfm JARDemoApp.jar manifest.txt –C ./bin
demo/app/JARDemoApp.class –C ./bin
demo/data/MyData.class

This assumes:
 you are issuing the jar command from within the directory of
D:\My Docs\se4091\JARDemo
 manifest.txt is in the same directory
 Demo/app and demo/data are the names of the packages such that all
class files are located in
D:\My Docs\se4091\JARDemo\bin\demo\app
or D:\My Docs\se4091\JARDemo\bin\demo\data
 the capitalization of the class filename is identical to the capitalization of the
class itself (be careful on Windows because the OS is case-insensitive but
Java is NOT)
Dileep Kumar G.
58
Manifest details
Manifest.txt is an text file containing the following text:

Manifest-Version: 1.0
Created-By: 1.6.0_03-b05 (Sun Microsystems Inc.)
Main-Class: demo.app.JARDemoApp

Dileep Kumar G.
59
To deploy your application, you just
have to copy the JAR file to
someplace (e.g. C:\temp) on the
target PC

To run the application bundled within a JAR file,


issue the following command:
java –jar
“C:\temp\JARDemoApp.jar”
Or create a shortcut containing the above
command

Dileep Kumar G.
60
If your JAR file references other
JAR files (like Helper.jar)…

The Manifest.txt must contain a reference to the


location of the other JAR file(s):

Manifest-Version: 1.0
Created-By: 1.6.0_03-b05 (Sun Microsystems Inc.)
Main-Class: demo.app.JARDemoApp
Class-Path: ./Helper.jar

Note that ./ specifies that Helper.jar in this case can be found in the same
directory folder as JARDemoApp.jar (i.e. they are both in C:\temp).

Dileep Kumar G.
61
Online tutorial
 “Packaging Programs in JAR files”
 http://java.sun.com/docs/books/tutorial/deploy
ment/jar/index.html

Dileep Kumar G.
62
Automating the Build Process
using ANT

Dileep Kumar G.
63
ANT is used in the Verification
phases of the SW lifecycle
The stages of developing a software application
 Requirements Analysis
 High-level Design
 Plan
 Low-level Design
 Implementation
 Unit Test
 Integration
 System Test
 Deploy
 Maintain

Dileep Kumar G.
64
What is ANT?
ANT (Another Neat Tool) is a utility that
automates the process of compiling and
building (jarring) Java project files

It can be run independently of Eclipse,


NetBeans, or any other Java development
environment

ANT only depends on the JDK utilities (Java


compiler, JAR utility, etc.)
Dileep Kumar G.
65
Why ANT?
Typically, large projects need to be built and
tested frequently during the Verification phase
 Builds are done daily, or even more frequently
 Usually by the people doing the verification
 ANT can completely automate the tasks of
 retrieving code from a Repository
 Completely recompiling all source (.java) files
 JAR’ing rebuilt class (.class) files
 Copying built files to a distribution directory for access
by testers

Dileep Kumar G.
66
For a standalone ANT engine, you
can Install ANT from www.apache.org

Eclipse comes with its own ANT “engine”, so you


don’t need to install a standalone version of ANT
unless you want to run ANT outside of Eclipse 67
The idea behind ANT and other
similar build automation tools
ANT is based on executing build scripts that describe
1. Targets: the end result – usually file(s) that need to be
created as the end “product” There may be one or more
 E.g. a JAR file targets defined
2. The dependencies of the target on other files or targets
 E.g. JAR file depends on .class files (and maybe Javadoc .html
files) that need to be built first There is typically a hierarchy of
 .class files depend on .java files dependencies; the final target
depends on intermediate
 .html files depend on .java files targets
3. The rules for creating the target(s):
 Use jar.exe utility to create a JAR file from .class files
 Use javac.exe is use to compile .java files into .class files
 Use javadoc.exe to process comments in .java files into .html
files Dileep Kumar G.
68
Anatomy of a simple ANT
script Every script starts with an xml statement
similar to this which identifies
this file as containing xml statements
<?xml version="1.0"?>
The project element names the Ant project, and optionally
specifies the default target, base directory, etc.
<project name="Ant demo script" default="dosomething" basedir=".">
Properties are name/value pairs that can be declared for
subsequent symbolic access within the Ant script.
<property name="message" value="Hello SE4091!"/>

Targets contain statements and rules that the Ant engine executes
in order to perform some task or achieve some goal.
<target name="dosomething" description="Prints a message.">

<echo message="The message is ${message}"/>


</target>
Echo is a very simple task. See the Ant manual for a list of
</project> other tasks at ant.apache.org/manual in the section “Overview of
Ant Tasks”

Dileep Kumar G.
69
Demonstration

Dileep Kumar G.
70
Creating Ant Buildfiles
 Typically, Ant's build file, called build.xml should
reside in the base directory of the project.
 However there is no restriction on the file name or its
location.
 Create a file called build.xml anywhere in your
computer with the following contents in it:

71
Ant Buildfiles
 The XML element project has three attributes :

 A target is a collection of tasks that you want to


run as one unit.
 In our example, we have a simple target to provide an
informational message to the user.

72
Ant Buildfiles
 The target element has following attributes :

73
Running Ant Buildfiles
 Select HelloWorld.xml in one of the navigation views and
choose Run As > Ant Build... from its context menu.
 The launch configuration dialog is opened on a launch
configuration for this Ant buildfile.
 This dialog allows the configuration of many aspects of
the way an Ant buildfile is run, but for now concentrate on
the Targets tab which allows the selection of which Ant
targets to run and their order. Select both targets and
leave the order as the default.
 Click the Run button.
 The Ant buildfile is run, and the output is sent to
the Console view.
Dileep Kumar G.
74
Creating a project builder Ant
buildfile in Eclipse
 Create a Java project named HW.
1. Create a Java source file named HelloWorld with a
main method.
2. Put a single System.out.println() statement in the main
method, and make it print a greeting of your choice.
3. Save changes.
 Create a file named projectBuilder.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="HW.makejar" default="makejar" basedir=".">
<target name="makejar" description="Create a jar for HW project">
<jar jarfile="HelloWorld.jar" includes="*.class" basedir="bin" />
</target>
</project>

75
 In one of the navigation views, select the HW project
and choose Properties from its context menu.
 In the project properties dialog, select Builders, then
click New....
 In the Choose configuration type dialog, select Ant
build, and click OK.
 The External Tools dialog appears. Set the name
to Makejar.
 In the Main tab, click the Buildfile Browse
Workspace... and set the Location to be
the projectBuilder.xml buildfile created above.
 Then click the Base Directory Browse Workspace... and
set the Base Directory to be the HW project.

76
77
 In the Refresh tab, we want to be sure that when
our HelloWorld.jar is created, we see it in Eclipse. So
check Refresh resource upon completion, then
select The project containing the selected resource in
the list of scoped variables.
 In the Targets tab, you can specify when this project
builder is executed and which targets. By default,
the default target is set to run After a "Clean"and Manual
Build.
 Apply the changes and click OK.
 Back in the project properties dialog, you will now see a
project builder named Makejar that is set to run after the
default Java builder. Click OK to save the project builder
and close the dialog.

78
Intoduction to Unit Testing

Using JUnit to structure Unit Testing

Dileep Kumar G.
79
How can you test your code?

Dileep Kumar G.
80
How can you test your app?
 Run the app with inputs that should produce a
known output, and verify the actual output
One problem with this approach may be that you can’t make
your app accept “bad” inputs; thus you may not be able to
force all possible if-then-else blocks of the app’s classes’
methods to execute

 Write a separate “test” program that is designed to


exercise the classes and methods of the “production”
app
A problem with this might be gathering the results of the
exercises and determining whether each one passed or
failed.
Dileep Kumar G.
81
What is Unit Testing?
 Creating special-purpose test code that
exercises specific classes of your application
is called Unit Testing
 Such test code usually exercises one method
at a time whenever possible.
 The tests usually include exercising the
methods in “boundary conditions” by force-
feeding the methods “bad” arguments, such
as nulls.
Dileep Kumar G.
82
What is JUnit?
 JUnit is an open source Java testing framework used to
write and run repeatable tests.

 It is built in to Eclipse.
 Like Ant, it can also run standalone

 JUnit is designed to automatically call “test” methods that


in turn test the “real” code.
 It can compare actual results the “test” received from a real
method vs. the results it expected, and report deviations.
 It does not guarantee that the methods it calls actually perform
meaningful tests
 You must write meaningful tests
 You must write “enough” tests to cover all possible situations
Dileep Kumar G.
83
Demonstration

Dileep Kumar G.
84
Analyzer.java
//This class analyzes Strings and determines various metrics such as vowel count.

package stringAnalyzer;
import java.util.regex.Pattern;
@SuppressWarnings("unused")

public class Analyzer {


private String text; // string to be analyzed
private int numVowels;// number of vowels found

private int numConsonants; // number of consonants found


private int numBlanks; // number of blanks found
private boolean isInit; // true only after analyze() has been called

/**
* The public constructor for this class
* @param s the String to be analyzed
* @throws an Exception if s is null
*/
public Analyzer(String s) throws Exception {
if( s == null )
throw new NullPointerException("null argument!");
text = s;
numVowels = 0;
numConsonants = 0;
numBlanks = 0;

analyze(); Dileep Kumar G.


} 85
//This method analyzes the specified text string for the number of vowels,
consonants, and blanks it contains.
private void analyze() {

// These are the vowel and consonant patterns used for matching characters in the String
being analyzed.
String vowels = new String("[aeiou]");
// [aeiou] is called a *regular expression*; means "any character within the brackets"
String consonants = new String("[bcdfghjklmnpqrtvwxyz]");

for( int i=0; i<text.length(); i++ ) {


// iterate through the string, one character at a time

if( Character.isSpaceChar(text.charAt(i)) )
// check for space character
numBlanks++;

CharSequence cs = text.subSequence(i, i+1); // extract a single character


boolean isVowel = Pattern.matches(vowels, cs); // uses the Pattern class to match reg exp
if( isVowel )
numVowels++;

boolean isConsonant = Pattern.matches(consonants, cs); // check for consonant


if( isConsonant )
numConsonants++;
}
}
Dileep Kumar G.
86
/**
* retrieves the number of vowels in the specified string
* @return number of vowels (>=0)
* @throws RuntimeException if analyze() has not been called prior to this method
*/
public int getVowelCount() throws RuntimeException {
return numVowels;
}

/**
* retrieves the number of consonants in the specified string
* @return number of consonants (>=0)
*/
public int getConsonantCount() throws RuntimeException {
return numConsonants;
}

/**
* retrieves the number of blanks in the specified string
* @return number of blanks (>=0)
*/
public int getSpaceCount() throws RuntimeException {
return numBlanks;
}
}

Dileep Kumar G.
87
AnalyzerApp.java
/**
* An application for demonstrating how to use JUnit for testing
*/
package stringAnalyzer;

/**
* @author Dileep
* This is the main class that controls the program
*/
public class AnalyzerApp {

/**
* @param args
* - not used
*/
public static void main(String[] args) throws Exception {
Analyzer a = new Analyzer("a b c d e");
System.out.println("Number of consonants= " + a.getConsonantCount());
System.out.println("Number of vowels= " + a.getVowelCount());
System.out.println("Number of blank spaces= " + a.getSpaceCount());
}

Output:
Number of consonants= 3
Number of vowels= 2
Number of blank spaces= 4 88
AnalyzerTests.java
package tests;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.*;
import org.junit.rules.ExpectedException;
import stringAnalyzer.Analyzer;
// This class is responsible for testing the Analyzer class. Requires JUnit 4.
public class AnalyzerTests {
// This is an example JUnit test method.
@Test
public void testABCDE() throws Exception {
System.out.println("\t testing for input 'a b c d e' ");
Analyzer a = new Analyzer("a b c d e");
final int nExpectedConsonants = 3;
int nActualConsonants = a.getConsonantCount();
assertEquals(nExpectedConsonants, nActualConsonants);
}
// @Test, it verifies the operation of the analyze method for an empty string
public void testEmptyStringAnalysis() throws Exception {
Analyzer a = new Analyzer(""); The @Test annotation tells JUnit that the public void method
final int nExpectedVowels = 0; to which it is attached can be run as a test case. Before
final int nExpectedConsonants = 0; running the method, Junit first runs the setUpBeforeClass()
method, then constructs a fresh instance of this class, then
final int nExpectedSpaces = 0; runs the setUp() method, and then finally invokes the
int nVowels = a.getVowelCount(); annotated method. Any exceptions thrown by the test will be
int nConsonants = a.getConsonantCount(); reported by JUnit as a failure. If no exceptions are thrown,
the test is assumed to have succeeded. After running each
int nBlanks = a.getSpaceCount(); @Test method, JUnit calls the tearDown() method. After all
assertEquals(nExpectedVowels, nVowels); @Test methods are run, JUnit calls tearDownAfterClass().
assertEquals(nExpectedConsonants, nConsonants);
Dileep Kumar G.
assertEquals(nExpectedSpaces, nBlanks);
89
}
// @Test , it verifies the operation of the analyze method for an string
// containing all possible vowels and consonants
public void testFullStringAnalysis() throws Exception {
Analyzer a = new Analyzer(
"abc def ghi jkl mno pqr stu vwx yz ABC DEF GHI JKL MNO PQR STU VWX YZ");
final int nExpectedVowels = 10;
final int nExpectedConsonants = 42;
final int nExpectedSpaces = 17;
int nVowels = a.getVowelCount();
int nConsonants = a.getConsonantCount();
int nBlanks = a.getSpaceCount();
assertEquals(nExpectedVowels, nVowels);
assertEquals(nExpectedConsonants, nConsonants);
assertEquals(nExpectedSpaces, nBlanks);
}

// TODO: to verify that a null string reference is correctly handled


// @Test // This test uses the try-catch idiom commonly used in JUnit 3
public void testNullStringConstruction1() {
System.out.println("\t testing for null-arg Exception using try-catch ");
try {
Analyzer a = new Analyzer(null); // null arg should cause an Exception
fail(); // fail if we get here, because Analyzer constructor should
// have thrown an Exception
} catch (Exception e) {
assertTrue(e.getMessage().equals("null argument!"));
}
}

Dileep Kumar G.
90
// @Test(expected= Exception.class)
// this test expects an Exception to be thrown somewhere
public void testNullStringConstruction2() throws Exception {
System.out.println("\t testing for null-arg Exception using
@Test(expected=Exception.class) ");
Analyzer a = new Analyzer(null);// null arg should cause an Exception
}
@Rule
public ExpectedException thrown = ExpectedException.none();

// @Test // this test expects an Exception with a specific message to be


// thrown
public void testNullStringConstruction3() throws Exception {
System.out.println("\t testing for null-arg Exception using ExpectedException ");
thrown.expect(IOException.class); // we expect an exception to be thrown
// in this test
thrown.expectMessage("null argument!"); // ...with a message string as indicated
Analyzer a = new Analyzer(null);// null arg should cause an Exception
}
/* The "boilerplate" code below belongs in all JUnit test classes */
private static int testNumber; // incremented with each individual @Test
// method that is run
@BeforeClass
// This method is called only once at the beginning, each time JUnit is run.
public static void setUpBeforeClass() throws Exception {
System.out.println("Preparing to run all unit tests...\n");
testNumber = 1; // initialize
Dileep Kumar G.
}
91
@AfterClass
// This method is called only once at the end, each time JUnit is run.
public static void tearDownAfterClass() throws Exception {
System.out.println("Finished running all unit tests.");
}

@Before
// This method is called right before each individual @Test method,
// but AFTER the class constructor is called.
public void setUp() throws Exception {
System.out.println(">>setUp test number " + testNumber);
}

@After
// This method is called right after each individual @Test method.
public void tearDown() throws Exception {
System.out.println("<<tearDown test number " + testNumber + "\n");
testNumber++;
}

// This constructor is called once for each @Test, before the setUp() method is called
public AnalyzerTests() {
System.out.println("AnalyzerTests constructor called...");
}

Dileep Kumar G.
92
Self-Review Questions
1. List out tools that exist for version control?
2. What are the features of distributed version
control?
3. List out Git commands?
4. Write code snippet for creating a jar file?
5. Write code snippet to demonstrate the
concept of unit testing using JUnit?

Dileep Kumar G.
93

You might also like