Download - Eclipse Jun It
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 1/43
Click to edit Master subtitle style
nSoftware Development Tools 5
nCOMP220nDr Vladimir Sazonov
nEclipse and JUnit:
nCreating and running
a JUnit test case
These slides are mainly based on “ Java Development with Eclipse” – D.Gallardo et al., Manning Publications., 2003
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 2/43
n22
nEclipse and JUnit
Eclipse ’s JDT provides a powerful, flexibleenvironment forn writing , running , and debugging Java code.
But developing quality software requires more
than that.Because of its open and extensible nature,Eclipse easily accommodates tools (plug-ins)of all sorts.
Here we examine JUnit as Eclipse ’s integral testing framework (plug-in).
Later, we will consider Ant plug-in in Eclipse.
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 3/43
n33
nPersistence project
Here we begin (but not finish!) developing asample application :
n a l igh twe i gh t pe r s i s t ence compon en t that
allows one to save data in files .
Persisting data means saving it, using someform of storage, so one can retrieve it later.
Our goal is to illustrate (at least partly) howJUnit testing framework may be used inEclipse during developing this application.
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 4/43
n44
nPersistence project
The first step is to create a new Java p ro j e c t, called
Persistence
with choosing:
“Create separate folders for sources and class files”.
(You already know how to do this.)
Create under src directory in this projectn the stub class FilePersistenceServices.java
n with some stub methods (see below),
n but w i t hou t the main() method
n under the n e w p a c k a g e
org.eclipseguide.persistence
or
your.personal.persistence.package
n check Generate Commentsn click Finish
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 5/43
n55
package org.eclipseguide.persistence;
public class FilePersistenceServices
{
public static boolean write(String fileName, int key, Vector v)
{
return false; // false – because the method is not yet implemented
}
public static Vector read (String fileName, int key)
{
return null; // null – just to return anything
}
}
nFilePersistenceServices.java
write() and read () (stub) methods are intended to
1. insert a key -numbered vector record v into a file withreturning true , if successful,
2. retrieve a vector record from a file by its key number.
Extend the resulting Java class in the editor as follows:
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 6/43
n66Note Red syn tax e r ro r ma rk s on the right and lefthand side of the editor
FilePersistenceServices.java
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 7/43
n77
nFilePersistenceServices.java
Red marks on the right and left hand side of theeditor "say":
" Vector cannot be resolved to a type".
In fact, this is because
n there is no import statement for the Vector class.
The easiest way to add it consists in usingEclipse’s Quick Fix feature:
n Click on one of the light bulbs (on left margin of
the Editor)
n Double click on suggested fix:
Import 'Vector' (java.util)
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 8/43
n88
Click on a light bulb (left to the Editor)
nFilePersistenceServices.java
double-click
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 9/43
n99
nFilePersistenceServices.java
This class should now be error-free because the aboveactions automatically generated new impo r tde c l a r a t i on :
import java.util.Vector;
Tidy up and save the file:
1. Right-click on the editor area and select
Source->Format
or do the same from the menuor use Ctrl+Shift+F
2. Right-click on the editor area and choose Save.
Fo rma t t i ng and sav i ng aren’t necessary, but theymake some of Eclipse’s automated features work better.
Some ye l l ow co l ou red wa rn i ng s (n o t errors)remain which mean that in corresponding places Vector should be replaced to Vector<String>.
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 10/43
n1010
nThe JUnit testing framework in Eclipse
We are ready to create a t e s t c a se :n a special Java class called JUnit Test Case class.
It is normal to have
one t e s t c l a s s fo r ea ch c l a s s i n t he p rog ram
and to name them by adding the su f f i x Test to the classname:
n FilePersistenceServices.java – given s ou r c e ( s t ub )c l a s s ;
n FilePersistenceServicesTest.java – corresponding t e s tc a s e ;
The easiest way to create JUnit test case classes is using n JUnit wi za rd in Eclipse .
Correct
thisl ine
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 11/43
n1111
nCreate test case stub by using theJUnit wizard in Eclipse
Right-cl ick on the file
FilePersistenceServices.java
in the Package Explorer and
Select
New ->JUni t Test CaseSee next slide
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 12/43
n1212
Accept the default values for
• Sou r c e f o l d e r ,
• Pac kage ,
• N a m e of test case, and
•C la s s unde r t e s t .
Check options for creating
stubs for setUp(),
tearDown(), (and optionallyGenerate Comments).
Click Next.
Create test case stub by using the JUnit wizard in Eclipse
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 13/43
n1313
In the next dialog boxcheck boxes for theFilePersistenceServices read() andwrite() methods to create s t ub t e s t
me t hod s for each of them.
Click Finish.
Confirm adding Junit 4 l ibrary to thebuild path.If Junit 4 will not appear in PackageExplorer under Persistence,
Create test case stub by using the JUnit wizard in Eclipse
then see the second half of Slide 46 from EclipseJava.ppt.
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 14/43
n1414
package org.eclipseguide.persistence;
import static org.junit. Assert.*;import org.junit. After;import org.junit.Before;import org.junit.Test;
public class FilePersistenceServicesTest
{@Before //Runs before each @Test method
public void setUp() throws Exception{}
@After //Runs after each @Test method
public void tearDown() throws Exception{}
@Test public void test Write()
{
fail("Not yet implemented");
}
@Testpublic void testRead (){
fail("Not yet implemented");
}
}
The resulting t e s t c a se stub created by the wizard
stub test methodsfor testing
write() andread()
stub methodsfor setUp() andtearDown()
Importing the necessaryJunit4 classes
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 15/43
n1515
nFurther work on the test case stubFilePersistenceServicesTest.java
Now we need to create a f i x t u re :
n data and objects for which annotated as@Test methods test Write() and
testRead() in a test case will be applied:
wThe annotated as @Before and @After
methods setUP() and tearDown() are
provided to set up and clean fixtures,wthey are run by JUnit, respectively, be fo re
and a f te r each @Test method (testXXX()).
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 16/43
n1616
§ Declare Vec to r va r i ab l e at the beginning of the test case class declaration
public void setUp() throws Exception{
v1 = new Vector();v1.addElement("One");v1.addElement("Two");v1.addElement("Three");
}
fixingsomeVector consistingof threestrings
public class FilePersistenceServicesTest{
Vector v1;
n
You will need to use Quick Fix light bulb to add Vector impo r t s ta t eme n t .n Set up the fixture , Vector v1, as follows:
Further work on the test case stubFilePersistenceServicesTest.java
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 17/43
n1717
n In the most cases tearDown() method is unnecessary.
n But we can implement it to r e l e a s e v1 as
n In general, tearDown() is used to r e l e a s e s y s t em
re sou r c e s (probably expensive!) that might not otherwisebe released.
Now, we are ready to run th i s t e s t case inEclipse.
protected void tearDown() throws Exception
{v1 = null; // release v1
}
Further work on the test case stubFilePersistenceServicesTest.java
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 18/43
n1818
nRunning the JUnit tests in Eclips
Runn i ng the JUnit tests in Eclips is similar torunning a Java application:
1. First make sure that the test c a s e you want to run
FilePersistenceServicesTest.java
is s e l e c t e d – either in the editor or on the Package Explorer view.
2. Select Run->Run As->JUn i t Tes t
JUnit view is automatically added, coveringPackage Explorer view.
(See next slide)
R i th t t i
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 19/43
n1919
nRunning the JUnit tests in Eclips
Red bar turns green once your class passesall tests successfully.
Our tests do not pass.
n nothing strange!
n the tests f a i l by trivial reason: being“Not yet implemented ”
n more precisely: they are de l i be ra t e l y im p l em en t ed t o b e f a i le d
Fu r t he r wo r k bo t h on t he s o u r ce f i l e
and on t he t e s t c a se i s r equ i r ed .Try to double-click
n on f a i l ed t e s t s in JUnit view,
n on the s e c on d l i n e of the Failure Trace,
n and also on various elements in Online view.
This will l e ad y ou t o co r re spond ingp l a ce s i n t he ed i t o r . (Very helpful!)
After viewing the test results, you can click onthe Package Explorer tab to return thisview on the top.
The JUnit test view.
Notice the red coloured bar!
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 20/43
n2020
nFurther work on the Test Case stub
Let us test whether read() and write() methods return
reasonable values by using more general JUnit assert* methods (instead of fail()).
assert* methods will be further discussed in our lectures.
n The boolean write() method should return true if it
succeeds in writing the values stored in the Vector in a
file:
public void test Write(){
// fail("Not yet implemented"); assertTrue("NOT WRITTEN???",
FilePersistenceServices. write("TestTable", 1, v1));
}
Writing datato file
should be
successful
file name key vector
Comment or
omit this line
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 21/43
n2121
nFurther work on the test case stub
n Analogously, for read() method we
expect it to pass the following test:
public void testRead (){
// fail("Not yet implemented");FilePersistenceServices. write("TestTable", 1, v1);Vector w =
FilePersistenceServices.read ("TestTable", 1);
assertEquals(v1, w);}
reading should produce the same valuewhich has been written beforehandexpected actual
Comment or omit this line
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 22/43
n2222
again
To r e - run , click Run buttonOur tests again do not pass!
Again try to double-click n on f a i l ed tes t s in JUnit view,
n on the second l i ne of the FailureTrace,
This will lead you to correspondingplaces in the editor.
For example, we can see thatn testWrite failed because of
assertTrue which expects true. Ourmessage "NOT WRITTEN???" helps tounderstand the reason.
n
testRead failed because of java.lang. AssertionError: expected :<[One, Two, Three]> but was: <null> .
All of this can help to understand thereason of test failures.
The JUnit test view appears.
Again red coloured bar!
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 23/43
n2323
You can get a little instant gratification by
n changing the r e t u rn v a l ue of the write() method in the
FilePersistenceServices class from false to true and
n commenting out the testRead() method in
FilePersistenceServicesTest class.
Selected code may be commented out oruncommented by Ctrl-/.
nRunning the JUnit tests in Eclips
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 24/43
n2424
To r e - run , click Run button
Now we see green bar:
n the only remaining testWrite() method succeded(of course, by trivial reason).
Recover the original versions of our files by using Undo (Ctrl-Z).
nRunning the JUnit tests in Eclips
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 25/43
n2525
nFurther testing-coding
Thus, two minimal tests and zero functionality!
But we should not expect anything else because the source code is just a stub .
Anyway, we have already seen how JUnit works in Eclipse.
To develop functionality of our source code,let us
n t e s t and code a t a f i ne r l eve l o f de ta i l .
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 26/43
n2626
nFurther testing-coding
To implement our methods
n boolean write(String fileName, int key, Vector v)
n Vector read (String fileName, int key)
we will need intermediate – he l p e r me t hod s
n vector2String()
n string2Vector()
This is an intermediate step to write/read vectors via their string representation into/from afile.
F th t ti di
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 27/43
n2727
nFurther testing-codingWe intend to store data in a text file line-by-line for eachrecord:
using comma-separated values (CSV)
Here "1","2",… serve as keys to locate a specific record.
E.g. [Antbook,Hatcher,Manning,2003] is vec to r or
r e co rd saved into the file as a s t r i ng under the key 2.
Each line in the file is a s t r i ng to be created first by themethod vector2String(Vector v, int key) which isno t ye t imp l eme n ted.
"1","One","Two","Three""2","Antbook","Hatcher","Manning","2003""3","Eclipse","Gallardo","Manning","2003"
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 28/43
n2828
nFurther testing-coding According to tes t - f i r s t philosophy , let’s start with
extending FilePersistenceServicesTest class:
1. Add the following String s1 attribute under the Vector v1 attribute
String s1 = "\"1\",\"One\",\"Two\",\"Three\"";
@Testpublic void test Vector2String(){
assertEquals(s1, FilePersistenceServices.vector2String(v1,1));
}
expected
actual
Recall that actually v1 = [One, Two, Three]
2. Extend @Test m e t h o d s in
FilePersistenceServicesTest class by n e w t e s t
m e t h o d which we expect to pass
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 29/43
n2929
nFurther testing-coding
But now red signs and light bulbs appear on the right and left
boarders of the Editor view witnessing on a syntax error in the test classwhich uses non-existing yet methods.
n Click on the light bulb which sugges t s to
w create automatically(!) the stub methodvector2String(Vector v, int key) in the sou r ce f i l e
FilePersistenceServices.
n Agree with this suggesstion by double clicking , and
n Continue editing the resulting method as i t i s shown i n t he nex t
s l i d e with the goal for it
w to pass t he above t e s t .
t 2St i added to Fil P i t S i
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 30/43
n3030
public static String vector2String(Vector v, int key){
String s = null;
StringBuffer buffer = new StringBuffer();
// start with key in quotation marks and commabuffer.append("\"" + Integer.toString(key) + "\",");// add quote delimited entry // for each element in Vector v:for (int i = 0; i < v.size(); i++){
buffer.append("\"");buffer.append(v.elementAt(i));buffer.append("\"");if (i != (v.size() - 1)) // if i is not last{
buffer.append(","); // Adds comma in case } // of not last element
} s = buffer.toString();
return s;}
vector2String() added to FilePersistenceServices
Do not forget to regularly format, Ctrl+Shift+F, and save your files.
F th t ti di
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 31/43
n3131
Run the tests again using
n
the first two tests still f a i l ,n but the new third test
pas se s ! ! ! n Indeed, we see the green
tick and the e m p t y Failure Trace
Not a complete success, but the new t e s t
testVector2String() succe s s f u l ly pa s se s !
nFurther testing-coding
F th t ti di
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 32/43
n3232
nFurther testing-codingn To implement string2Vector(String s), let’s first
n add the following new @Test method to
FilePersistenceServicesTest
n suggests again to implement string2Vector() in
the source file (as we are t e s t i ng a non-ex i s t i ngme thod ).
n We also need to use Java’s StringTokenizer class ton parse the String and into tokens
n add each token to a Vector as follows in the next slide:
@Testpublic void testString2Vector(){
assertEquals(v1,FilePersistenceServices.string2Vector(s1));
}
expecte
d
actual
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 33/43
n3333
nFurther testing-coding
public static Vector string2Vector(String s){
Vector v = new Vector();
// use comma and double quotes as delimiters
StringTokenizer st = new StringTokenizer(s, "\",");
while (st.hasMoreTokens()){
v.addElement(st.nextToken());}
return v;
}
string2vector() added to FilePersistenceServices
parsing string s
into tokens andadding them tovector v
E.g. string ""One","Two","Three"" transforms to vector [One,Two,Three].
suggests to import java.util.StringTokenizer;
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 34/43
n3434
However, the test for
string2Vector fails:n Failure Trace in the JUnit view
indicates that the comparison of
w the expected value v1 and
w the returned string2Vector(s1) ared i f f e ren t:
java.lang. AssertionError:
expected :<[One, Two, Three]>
but was:<[1, One, Two, Three]>
CORRECT implementation of themethod string2Vector() tomake testString2Vector passing.n Just ignore the initial token 1
(how?)
n Run the test again; it shouldsucceed!
Further testing-coding
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 35/43
n3535
nFurther testing-codingn Iimplement yourself another method
in FilePersistenceServices class, but ...
n Preliminary write testGetKey() inFilePersistenceServicesTest classs:
public static int getKey (String s){???}
@Testpublic void testGetKey(){
assertEquals(1,FilePersistenceServices.getKey (s1));}
expected actual
suggests further actions:
to create and implement!!! getKey ...
Run the test for GetKey()again to assure that it
Further testing coding
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 36/43
n3636
nFurther testing-codingOur work on Persistence project is not finished yet.
See yourselves further steps and details in Eclipse Book.
Our goal was to give you a flavour of Test Driven approach to programming, and how Eclipse helps in this approach.
This only could help you to start using this approach.
Try to use this approach in your programming practice.
Read more on JUnit testing to study it deeper and to learnbest practices of its using.
Then you will get a be t t e r unde r s t and i ng and somebene f i t s of this approach.
Recall that t e s t ing m any t imes a d ay w i l l r a t he rn s a v e y ou r t ime , and
n make your work much more c om fo r t a b l e and c on f i d en t .
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 37/43
The button makes running JUnit test classes InEclipse very easy.
However, JUnit in itself is a Java application and
can be run just from the command line .
E.g., from the directory Persistence
corresponding to our project we can
n comp i l e both source code and the test class and then
n run the test class as follows:
n
3737
Running tests from the commandline
Compiling and Running tests from the
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 38/43
n
3838
Compiling and Running tests from the command lineC:\workspace\Persistence>javac -d bin src\org\eclipseguide\persistence\*.java
C:\workspace\Persistence>java -cp bin;C:\JAVA\junit4.8.2\junit-4.8.2.jarorg.junit.runner.JUnitCore org.eclipseguide.persistence.FilePersistenceServicesTest
JUnit version 4.8.2
.E.E...
Time: 0.015
There were 2 failures:
1) testWrite(org.eclipseguide.persistence.FilePersistenceServicesTest)java.lang. AssertionError: NOT WRITTEN???
<many lines skipped>
2) testRead (org.eclipseguide.persistence.FilePersistenceServicesTest)
java.lang. AssertionError: expected :<[One, Two, Three]> but was:<null>
<many lines skipped>
FAILURES!!!
Tests run: 5, Failures: 2
Do not forget to recompile each time!!!
Your messageto yourself
E (error) means that the previous testXXX
methods – shown as one dot (.) – failed
Complicated commands and a lot of unimportant lines (skipped) makes thisrunning tests not very comfortable.
Last lines show us that we shouldlook upwards for the failures
Test
runner
Test case torun
Class
path
Where (direction) tocompile
Description of a test failure
n Essential steps
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 39/43
n
3939
nDetailed Summary: Essential steps,advantages, and peculiarities of creating and
running a JUnit test case in Eclipse.
JUnit is included in Eclipse as a well-integrated plug-in .
Eclipse has a wizard creating test cases from existing Java Classes to betested.
n
Therefore it makes sense to create first aJava Class to be tested, but initially onlywith method stubs .
n Essential steps
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 40/43
n
4040
nDetailed Summary: Essential steps,advantages, and peculiarities of creating and
running a JUnit test case in Eclipse.
The wizard automatically suggests the default names forn source folder (src),n folder where to compile ( bin),n package,n test case ClassTest
corresponding to the name of the tested Class,
The wizard also suggests the options for
creating s t ub s methodsn setUp() and tearDown()
annotated as @Before and @After,respectively.
n Essential steps
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 41/43
n
4141
In the Next step the wizard presents the options tocreate @Test method stubs testXXX() to test each
of the methods xXX() in the Class under testing.
All of these considerably alleviates and even
automates the preliminary routine editing work tocreate a test case.
Next step is to finish creating test case: n to setUp() (and, optionally, tearDown()) a f i x t u re , and
to finish writing testXXX() methods.
The latter is, of course, no t an automated part of work.
Nevertheless, Eclipse can help, as in the case of
editing of any Java code.
nDetailed Summary: Essential steps,advantages, and peculiarities of creating and
running a JUnit test case in Eclipse.
n Essential steps
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 42/43
n
4242
Running JUnit test cases in Eclipse is similarto running a Java application (just by mouseclick) and has the same convenience incomparison with command line running.
It automatically adds JUnit view whichinstantly shows by the red/green barn whether our Class passes all the unit tests
successfully,
n the information about each failed @Test annotatedmethod testXXX(),
n whether it failed because of some of its assertion method ,
n or due to a compilation or runtime error .
nDetailed Summary: Essential steps,advantages, and peculiarities of creating and
running a JUnit test case in Eclipse.
n Essential steps,
8/3/2019 Eclipse Jun It
http://slidepdf.com/reader/full/eclipse-jun-it 43/43
n
For each failed @Test method testXXX() there is aFailure Trace in JUnit view which can help to find outthe reason of the failure .
To investigate further, the powerful debugge r tool of
Eclipse can be used as well.(We have not considered this in detail, but you should
know about existence of debugger in Eclipse)
After correcting all errors and passing all tests
n the cycle on further writ ing tests and adapting thesource code to pass tests is repeated ...
n until a satisfactory source code will be obtained.
Detailed Summary: Essential steps,advantages, and peculiarities of creating and
running a JUnit test case in Eclipse.