junit-fundamentals.ppt
TRANSCRIPT
-
8/9/2019 junit-fundamentals.ppt
1/27
JUNIT
Jan 31, 2015
-
8/9/2019 junit-fundamentals.ppt
2/27
Test suites2
Obviously you have to test your code to get itworking in the frst place You can do ad hoctesting (testing whatever occurs to you at
the moment! or You can build a test suite(a thorough set o" tests that can
be run at any time
#isadvantages o" writing a test suite It$s a lot o" e%tra programming
True&but use o" a good test "rameworkcan help 'uite a bit You don$t have time to do all that e%tra work
False&%periments repeatedly show that test suites reducedebugging time more than the amount spent building the test
suite )dvantages o" having a test suite
Your program will have many "ewer bugs It will be a loteasier to maintain and modi"y your program
This is a hugewin "or programs that! unlike class assignments!
get actual use*
-
8/9/2019 junit-fundamentals.ppt
3/27
%ample+ Old way vs, new
way
int max(int a, int b) { if (a > b) { return a; } else { return b; }}
void testMax() { int x = max(3, 7); if (x != 7) { Systemoutrintln("max(3, 7) #ives " $ x); } x = max(3, %7); if (x != 3) {
Systemoutrintln("max(3, %7) #ives " $ x); }}
ubli& stati& void main(Strin#' ar#s) { ne My*lass()testMax();}
+estvoid testMax() { assert-.uals(7, max(3, 7)); assert-.uals(3, max(3, %7));}
3
-
8/9/2019 junit-fundamentals.ppt
4/27
-. approach to testing4
In the %treme .rogramming approach! Tests are written be"ore the code itsel" I" code has no automated test case! it is assumed not to work ) test "ramework is used so that automated testing can be
done a"ter every small change to the code
This may be as o"ten as every / or 01 minutes I" a bug is "ound a"ter development! a test is created to keep
the bug "rom coming back
2onse'uences 3ewer bugs
4ore maintainable code 2ontinuous integrationuring development! the program
always works&it may not do everything re'uired! but what itdoes! it does right
-
8/9/2019 junit-fundamentals.ppt
5/27
JUnit5
JUnitis a "ramework "or writing tests JUnit was written by rich 5amma (o" Design
Patterns"ame and 6ent 7eck (creator o" -.methodology
JUnit uses Java$s re8ectioncapabilities (Javaprograms can e%amine their own code
JUnit helps the programmer+ defne and e%ecute tests and test suites "ormali9e re'uirements and clari"y architecture write and debug code integrate code and always be ready to release a
working version JUnit is not included in :un$s :#6! but almost all
I#s include it
-
8/9/2019 junit-fundamentals.ppt
6/27
Terminology6
) test f%turesets up the data (both ob;ects andprimitives that are needed to run tests %ample+ I" you are testing code that updates an employee
record! you need an employee record to test it on
) unit testis a test o" a singleclass
) test casetests the response o" a single method to aparticular set o" inputs
) test suiteis a collection o" test cases ) test runneris so"tware that runs tests and reports
results
)n integration testis a test o" how well classes worktogether JUnit provides some limited support "or integration tests
-
8/9/2019 junit-fundamentals.ppt
7/27
Once more! in pictures7
) unit testtests themethods in a single class
) test casetests (inso"ar aspossible a single method You can have multiple test
cases "or a single method ) test suitecombines unit
tests
The test f%tureprovidesso"tware support "or all this The test runnerruns unit
tests or an entire test suite Integration testing(testing
that it all works together is
not well supported by JUnit
test suite
unit test (for one &lass)
anot/er unit test
test &ase (for one met/od)
anot/er test &ase
test &ase (for one met/od)
anot/er unit test
anot/er test &ase
anot/er test &ase
anot/er test &ase
test fixture
test runner
anot/er test &ase
-
8/9/2019 junit-fundamentals.ppt
8/27
-
8/9/2019 junit-fundamentals.ppt
9/27
9
#efne a method (or several methods to be e%ecuted beforeeach test Initiali9e your variables in this method! so that each test
starts with a "resh set o" values +6efore
ubli& void set() { ro#ram = ne My4ro#ram(); some5ariable = 8999;}
You can defne one or more methods to be e%ecuted a"ter
each test Typically such methods release resources! such as fles Usually there is no need to bother with this method
+2fterubli& void tear:on() {
}
-
8/9/2019 junit-fundamentals.ppt
10/27
) simple e%ample
:uppose you have a class 2rit/meti&with methods int multily(int x, int y),and boolean is4ositive(int x)
imort or#0unit1;imort stati& or#0unit2ssert1;
ubli& &lass 2rit/meti&est {
}
+estubli& void testMultily() { assert-.uals(, 2rit/meti&multily(
-
8/9/2019 junit-fundamentals.ppt
11/27
)ssert methods I11
-
8/9/2019 junit-fundamentals.ppt
12/27
%ample+ *ounterclass12
3or the sake o" e%ample! we will create and test atrivial ?counter@ class The constructor will create a counter and set it to 9ero The in&rementmethod will add one to the counter and return
the new value
The de&rementmethod will subtract one "rom the counterand return the new value
-
8/9/2019 junit-fundamentals.ppt
13/27
JUnit tests "or *ounter
ubli& &lass *ounterest { *ounter &ounter8; de&lare a *ounter /ere
+6efore void set() { &ounter8 = ne *ounter(); initiali@e t/e *ounter /ere
}
+est ubli& void testn&rement() { assertrue(&ounter8in&rement() == 8); assertrue(&ounter8in&rement() ==
-
8/9/2019 junit-fundamentals.ppt
14/27
The *ounterclass itsel"
ubli& &lass *ounter {int &ount = 9;
ubli& int in&rement() { return &ount $= 8;
}
ubli& int de&rement() { return &ount %= 8;}
ubli& int #et*ount() { return &ount; }}
Is JUnit testing overkill "orthis little classB
The %treme .rogrammingview is+ If it isnt tested, itdoesnt work
You are not likely to havemany classes this trivial in areal program! so writingJUnit tests "or those "ewtrivial classes is no big deal
O"ten even -. programmersdon$t bother writing tests
"or simplegetter methodssuch as #et*ount()
-
8/9/2019 junit-fundamentals.ppt
15/27
Warning:e.uals15
You can compareprimitiveswith== Java has a methodxe.uals(y)! "or comparing objects
This method works great "or Strin#s and a "ew other Java classes 3or ob;ects o" classes thatyoucreate!youhave to defne e.uals
assert-.uals(expected, actual) uses CC or e.uals
To defne e.uals "or your own ob;ects! defne eactlythis method+ubli& boolean e.uals(Ab0e&t obj) {...} The argument must be o" type Ab0e&t! which isn$t what you
want! so you must castit to the correct type (say! 4erson+ ubli& boolean e.uals(Ab0e&t somet/in#) {
4erson = (4erson)somet/in#; return t/isname == name; test /atever you liBe /ere}
-
8/9/2019 junit-fundamentals.ppt
16/27
)ssert methods II16
assert-.uals(expected, actual)assert-.uals(Strin# message, expected, actual)
expected and actual must be both ob;ects orthe same
primitive type
3or ob;ects! uses your e'uals method! if you have defned it
properly! as described on the previous slide
assertSame(Ab0e&t expected, Ab0e&t actual)assertSame(Strin# message, Ab0e&t expected, Ab0e&t actual)
)sserts that two arguments re"er to the sameob;ect
assertDotSame(Ab0e&t expected, Ab0e&t actual)assertDotSame(Strin# message, Ab0e&t expected, Ab0e&t actual)
)sserts that two ob;ects do not re"er to the same ob;ect
-
8/9/2019 junit-fundamentals.ppt
17/27
)ssert methods III17
assertDull(Ab0e&t object)assertDull(Strin# message, Ab0e&t object)
)sserts that the ob;ect is null (undefned
assertDotDull(Ab0e&t object)
assertDotDull(Strin# message, Ab0e&t object) )sserts that the ob;ect is null
fail()
fail(Strin# message)
2auses the test to "ail and throw an 2ssertion?ailed-rror
Use"ul as a result o" a comple% test! when the otherassert methods aren$t 'uite what you want
-
8/9/2019 junit-fundamentals.ppt
18/27
-
8/9/2019 junit-fundamentals.ppt
19/27
:pecial "eatures o" +est19
You can limit how long a method is allowed to take This is good protection against infnite loops The time limit is specifed in milliseconds The test "ails i" the method takes too long
+est (timeout=89)
ubli& void #reat6i#() { assertrue(ro#rama&Berman(, ) > 89e8
-
8/9/2019 junit-fundamentals.ppt
20/27
TestD#riven #evelopment(T##20
It is diEcult to add JUnit tests to an e%isting program The program probably wasn$t written with testing in mind
It$s actually better to write the tests beforewritingthe code you want to test
This seems backward! but it really does work better+
-
8/9/2019 junit-fundamentals.ppt
21/27
:tubs21
In order to run our tests! the methods we are testinghave to e%ist! but they don$t have to be right
Instead o" starting with ?real@ code! we start with stubs&minimal methods that always return the same values ) stub that returns voidcan be written with an empty body ) stub that returns a number can return 9or %8or EEE! or
whatever number is most likely to be wrong ) stub that returns a booleanvalue should usually return false ) stub that returns an ob;ect o" any kind (including a Strin#or
an array should return null
-
8/9/2019 junit-fundamentals.ppt
22/27
Ignoring a test22
The +#noreannotation says to not run a test
+#nore(" donFt ant :ave to Bno t/is doesnFt orB")
+est
ubli& void add() {
assert-.uals(, ro#ramsum(
-
8/9/2019 junit-fundamentals.ppt
23/27
Test suites23
You can defne a suite o" tests
+GunHit/(value=Suite&lass)
+Suite*lasses(value={
My4ro#ramest&lass, 2not/erest&lass,
Iet2not/erest&lass
})
ubli& &lass 2llests { }
-
8/9/2019 junit-fundamentals.ppt
24/27
JUnit in clipse24
I" you write your method stubs frst (as on the previous slide!clipse will generate test method stubs "or you To add JUnit = to your pro;ect+
:elect a class in clipse 5o to ?ile De Jnit est *ase 4ake sure De Jnit testis selected 2lick where it says ?*li&B /ere to add Jnit @ 2lose the window that appears
To create a JUnit test class+ #o steps 0 and > above! i" you haven$t already 2lickDext>
Use the checkbo%es to decide which methods you want test cases"orFdon$t select Ab0e&tor anything under it I like to check ?create tasks!@ but that$s up to you
2lick ?inis/ To run the tests+
2hoose Gun Gun 2s Jnit est
-
8/9/2019 junit-fundamentals.ppt
25/27
Giewing results in clipse25
6ar is #reen ifalltests ass,
red ot/erise
Gan 89 of
t/e 89 tests
Do tests
failed, but
Somet/in# unexe&ted
/aened in to tests
/is test assed
Somet/in# is ron#
:eendin# on your
referen&es, t/is
indo mi#/t s/o
onlyfailed tests
/is is /o
lon# t/e
test tooB
-
8/9/2019 junit-fundamentals.ppt
26/27
Hecommended approach26
-
8/9/2019 junit-fundamentals.ppt
27/27
The nd27
If you dont unit test then you arent a software engineer, you are a
typist who understands a programming language.
--Moses Jones
1. Never underestimate the power of one little test.
2. There is no such thing as a dumb test.
3. Your tests can often find problems where youre not expecting
them.
4. Test that everything you say happens actually does happen.
5. If its worth documenting, its worth testing.
--Andy Lester