AM FL Y JUnit Recipes TE Practical Methods for Programmer Testing J.B.Rainsberger with contributions by Scott Stirling MANNING Team-Fly® JUnit Recipes JUnit Recipes Practical Methods for Programmer Testing J.B RAINSBERGER with contributions by SCOTT STIRLING MANNING Greenwich (74° w long.) Licensed to Wong Wing Kee To my mother, Joan I wish I had finished this in time For online information and ordering of this and other Manning books, please visit www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact: Special Sales Department Manning Publications Co 209 Bruce Park Avenue Greenwich, CT 06830 Fax: (203) 661-9018 email: manning@manning.com ©2005 by Manning Publications Co All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books they publish printed on acid-free paper, and we exert our best efforts to that end Manning Publications Co 209 Bruce Park Avenue Greenwich, CT 06830 Copyeditor: Mark Goodin Typesetter: Martine Maguire-Weltecke Cover designer: Leslie Haimes ISBN 1932394230 Printed in the United States of America 10 – VHG – 07 06 05 04 Licensed to Wong Wing Kee brief contents PART PART THE BUILDING BLOCKS 1 ■ Fundamentals ■ Elementary tests ■ Organizing and building JUnit tests ■ Managing test suites ■ Working with test data ■ Running JUnit tests ■ Reporting JUnit results ■ Troubleshooting JUnit 233 22 71 102 136 173 188 TESTING J2EE 257 ■ Testing and XML 265 10 ■ Testing and JDBC 308 11 ■ Testing Enterprise JavaBeans 12 ■ Testing web components 443 13 ■ Testing J2EE applications 508 370 v Licensed to Wong Wing Kee vi BRIEF CONTENTS PART MORE JUNIT TECHNIQUES 541 14 ■ Testing design patterns 15 ■ GSBase 572 16 ■ JUnit-addons 17 ■ Odds and ends 543 585 603 APPENDICES 629 A ■ Complete solutions B ■ Essays on testing C ■ Reading List 629 673 696 Licensed to Wong Wing Kee contents foreword xv preface xvii acknowledgments xix about this book xxii about the cover illustration PART xxx THE BUILDING BLOCKS 1 Fundamentals Elementary tests 1.1 1.2 1.3 1.4 2.1 2.2 2.3 2.4 2.5 2.6 What is Programmer Testing? Getting started with JUnit 10 A few good practices 17 Summary 20 22 Test your equals method 26 Test a method that returns nothing 33 Test a constructor 37 Test a getter 41 Test a setter 44 Test an interface 48 vii Licensed to Wong Wing Kee viii CONTENTS 2.7 2.8 2.9 2.10 2.11 Organizing and building JUnit tests 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 Test a JavaBean 54 Test throwing the right exception 56 Let collections compare themselves 61 Test a big object for equality 63 Test an object that instantiates other objects 71 Place test classes in the same package as production code 74 Create a separate source tree for test code 77 Separate test packages from production code packages 79 Factor out a test fixture 83 Factor out a test fixture hierarchy 87 Introduce a Base Test Case 90 Move special case tests to a separate test fixture Build tests from the command line 94 Build tests using Ant 96 Build tests using Eclipse 99 Managing test suites 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 66 102 Let JUnit build your test suite 103 Collect a specific set of tests 107 Collect all the tests in a package 111 Collect all the tests for your entire system 114 Scan the file system for tests 116 Separate the different kinds of test suites 120 Control the order of some of your tests 123 Build a data-driven test suite 127 Define a test suite in XML 133 Licensed to Wong Wing Kee 92 CONTENTS Working with test data 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 6.3 6.4 6.5 6.6 Use Java system properties 138 Use environment variables 142 Use an inline data file 145 Use a properties file 147 Use ResourceBundles 152 Use a file-based test data repository 154 Use XML to describe test data 156 Use Ant’s task to work with a database 157 Use JUnitPP 159 Set up your fixture once for the entire suite 161 Perform environment setup once for multiple test runs 164 Use DbUnit 170 Running JUnit tests 6.1 6.2 173 See the name of each test as it executes See the name of each test as it executes with a text-based test runner 178 Execute a single test 180 Execute each test in its own JVM 181 Reload classes before each test 182 Ignore a test 185 Reporting JUnit results 7.1 7.2 7.3 7.4 7.5 136 177 188 Using a Base Test Case with a logger 190 Using Log4Unit 194 Getting plain text results with Ant 198 Reporting results in HTML with Ant’s task 202 Customizing XML reports with XSLT Licensed to Wong Wing Kee 205 ix 708 INDEX database connection 161 as test resource 170 database fixture 341 database meta data 334 alternatives to 331 making assertions on 329 database schema 327, 329, 366, 406 dependency on 333 enabling change 328 database servers 165 DatabaseMetaData.getSchemas() 330 databases 249, 309 and entity beans 375 and message-driven beans 421 and test data 137, 139, 157, 170, 346, 597 as a test resource 586, 593 collective ownership 327 connection parameters 142 development 352 exclusive access 406 four for testing 309 free alternatives 350 integration 310 issues testing against 334 large data sets 171 leftover data 332 legacy 363 meta data 329 minimizing tests against 261, 312 multiple schemas 363 ownership issues 350 problems using 157, 401 reducing dependency on 261 referential integrity 406 resetting state between tests 138 shared 309, 349 stored procedures 366 testing entity beans without 389, 409 testing the schema 328, 352 testing with 333, 360, 398, 557, 596, 599, 672, 681 testing without 317, 322, 332, 357–359, 599 DatabaseTestCase 170 data-driven tests 103, 127, 133 and Cactus 132 dataset 361, 364 DataSource 162, 325, 594 DbUnit 91, 138, 170, 360, 363, 365, 399, 596 flat XML format 360 limitations 362 dbunit.qualified.table.names 363 DDL See Data Definition Language deadlock 177–178, 600 debug mode debug(Object message, Throwable t) See Log4Unit debugger 4–5, 7, 74 debugging 4, 20, 178, 190, 334, 500, 536, 676 declarative security 525, 535 how not to test 529 declarative transactions 536 default test suite 235, 237, 243 DefaultConsole 601 DefaultDataSet 362 defects 8, 36, 474, 614, 675 caused by missing test 38, 56, 110 come back 4, 182 diagnosing 297, 305 hiding 351, 478, 616 impact of 371, 451 in an external library 186 in J2EE 1.3 412 in the platform 394 isolating 20–21, 378, 399 low-priority 186 mean time to find 114, 607 pattern 352 recurring 302, 397 delegate 379 delegation 676 DELETE_ALL 170 dependency 259, 282, 310, 312, 333, 371 avoiding 485 checking 204 database tables 334 eliminated 613 on file system 604 deployed component alternatives to testing 272 deploying 513 database schema objects 352 JSP tag library 474 tests 590 deployment 372, 399, 506 complexity of 378 simulating 423 deployment descriptors 266, 415, 529, 536, 538 and ServletUnit 445, 454–455 forgetting to write 474 testing 272, 399, 475, 477 deployment information hard coding 513 deployment problems 513 deployment script 591 Deployment Tests 280, 409, 439, 477, 536, 591 design indicator of good 460 testable 452 design improvement 66, 108 See also refactoring design pattern 162, 544 Abstract Factory 544 Action 45 Bridge 373, 376 Command 45, 55, 663 Composite 544 Decorator 162, 179, 427, 544, 665, 676 Event Listener 545, 576 See also design pattern, Observable Event Source 545, 550 See also design pattern, Observer Factory 562 Front Controller 490 Model View Controller 371 Null Object 691 Observable 544, 550, 555, 574, 621 Observer 215, 544–545, 548, 621 Prototype 580 refactoring towards 544 Registry 593 Remote Facade 379, 386 Singleton 68, 169–170, 181–184, 440, 544, 556–557, 559, 561 Strategy 509 suggested by tests 544 Template Method 566 Wrapper See design pattern, Decorator Licensed to Wong Wing Kee INDEX design problem 346 destroy() 480 DetailedDiff 288 Diasparsoft Toolkit CollectionUtil 331 EntityBeanMetaDataTest 403 ExceptionalClosure 59 FakeHttpSession 490 FileSystemWebConnection 491 FileSystemWebResponse 491 ForwardingServlet 459 GoldMasterFile 462 HttpUtil 516 JDBC utilities 330, 660 RequestDispatcherAdapter 490 ValueObjectEqualsTest 64 DiFalco, Robert 181 Diff XMLUnit 275 Diff engine XMLUnit 281 Difference 284 DifferenceConstants 283 ATTR_VALUE 283 TEXT_VALUE 283 differenceFound() 284–285 DifferenceListener 272, 280, 282, 285, 287 differences ignoring in XML documents 272, 281 in XML documents 274, 289 multiple in XMLUnit tests 288 DirectorySuiteBuilder 119, 175, 590, 596 compared to RecursiveTestsuite 119 disable 185 distribution 386 doAfterBody() 470 DocBook 273, 276 Doctor Dobbs Journal 159 Document Object Model 278, 283, 294, 476 custom 287 Document Type Definition 272, 303, 403, 521 network connectivity 279 using locally 280 doEndTag() 470 doFilter() 503 709 ed bar 174 EJB 162, 259, 420 failure when narrowing 253 suitability 371 why we use it 386 See also Enterprise JavaBeans EJB container 385, 392, 397, 399, 410, 530 avoiding 372–373, 392 live 374, 377, 398, 414, 672 mocking 392 simulate 374, 386, 392 testing without 400 EJB implementation class instantiating directly 392, 411 EJB server See EJB container EJB specification 382, 399 ejbCreate() 385, 427 ejbLoad() 410 EJBQL 398, 401, 406 emacs 200 email 199 encapsulation 37, 45 endo-testing 690 End-to-End Tests 7, 262, 494, 510, 519 alternatives to 446, 457, 470, 474, 491 as safety net 335 CMP entity beans 375, 399, 407 for legacy code 455 for security 525 HtmlUnit 513 organizing 79, 101, 120, 123 purpose of 509 test fixtures 87 Enterprise JavaBeans 253, 371, 496 as thin as possible 372 lifecycle methods 393, 408, 659 entity beans 374, 386, 397, 400, E 408, 440, 536, 653 BMP 376, 408 Eames, Mark 444 reducing the cost of *.ear 395 testing 406 EAR file 143 testing meta data 401 EasyMock 67, 318, 409, 437, 560, trade-off between BMP 690, 695 and CMP 374 alternative to Self-Shunt 555 examples of use 436, 438, 488, EntityContext 409–411 549, 626–627, 669 environment setup 164 Eclipse 99, 140, 180, 251, 596, 610 environment variables 138, Java Build Path 235 142–144, 147, 235 doGet() 456 DOM 220, 291 See Document Object Model Domain Model 27, 379, 381, 383–384, 386, 587 domain object 318 converting to database object 314 DOMParser 295 don’t test the platform EJB container 375, 397, 399 Java compiler 40 JDBC 310 JMS server 433 web container 505, 525, 529 doPost() 447, 456, 488–490, 499 doRunTest() 215 doStartTag() 470 downloading JUnit 10 DTD 304, 401, 477 See also Document Type Definition DuplicateKeyException 399 duplication 9, 59, 248, 309, 316, 420, 548 and shared test resources 593 eliminating 25, 35, 89, 617 extracting into test fixture 73, 83 in database tests 310, 337, 362 in production code 318, 446 in test names 92, 110 in tests 92, 113, 127, 432, 637 of assertions 301, 403, 604, 617 of production code in tests 563–565 of production logic in fake objects 692 dynamic content 496 dynamic invocation handler 576 Licensed to Wong Wing Kee INDEX exception 15 expected 56 ignoring expected ones 58 object-oriented test approach 58 throwing from tests 105 throwing the right one 56 unexpected 57 ExceptionalClosure 59 excluded.properties 250, 252, 254 location on file system 251 multiple copies 251 expectations 8, 392 expected result 25 expected value 24, 34, 282 comparing to actual value 24 expensive tests 681 isolating 689 exploratory testing 7, 20 extending JUnit 189, 586 external data 346 external library class loading problems 250 handling defects in 186 external resource 249, 593, 613, 681 avoiding 260, 334, 376, 442, 510, 608 effect on test execution speed 114 extracting into test fixture 86 mitigating the cost of 438 simulating 415 tests dependency on 120 determining the cause 293 how it occurs 56 message 15, 59, 90, 177, 589 multiple in test 244 notification 216 signaling 15 what it indicates 16 failure message 59, 131, 271, 287, 333, 442, 554, 618 customized 620 misleading 333 specialized 290 XMLUnit 288 fake 287, 489, 516, 545, 669, 685, 691–693 fake method 67 fake objects 486 false failures 418, 475, 513, 523, 607, 612 false positive 432 feedback 7–8, 21, 111, 250, 371 file cleaning up between tests 604 reading data from 608 file system 149, 280, 458, 466, 604–605, 607 cleaning up between tests 605 load web pages from 491 scan for tests 117 testing without 606, 608 file system operations asynchronous nature 605 FileAssert 620 filename relative 610 201 filter 283 F See also web resource filter FilterChain 503 factory method 562 finally 336 fail fast 694 finder methods 398 fail() 57, 330 finite state machine 514 failed assertion See failure Fit 135, 509 failed test See failure FitNesse 509–510 failing status code 528 fixtures 18, 83, 521, 532, 605, 686 failing test amount of duplication 89 one per incorrect behavior 245 and order-dependent FailingHttpStatusCodeException tests 123–124 528 and Parameterized Test failure 16, 57, 90, 382, 545 Case 129, 132, 181 and Self-Shunt 432 affecting other tests 106 TE equality 25–26, 31 approximating with appears equal 581 of XML documents 269 equals() 25–29, 32, 586–587, 677 and compareTo() 588 and EventCatcher 576 and JavaBeans See appearsEqual() 581 and object cloning 573, 579–580 and testSerliaization() 578 and TestUtil.testClone() 573 and XML documents 287 description of contract 27 for collections 62 for Value Objects 27 implementing correctly 26 not implemented correctly 581 testing 26 testing without EqualsTester 29 when to implement 45 EqualsHashCodeTestCase 32, 63, 65 EqualsTester 28–29, 32–33, 63, 678, 681 example of using 28 parameters 28 special handling of subclasses 28 equivalence relation 27 error 16, 57, 545 how it occurs 56 notification 216 what it indicates 16 what it means 57 error conditions 490 error handling for JMS components 427 error-case testing 437 ERwin 328 Evans, Eric 698 event handler 213 event listener 81, 693 universal 576 event source 81, 576, 693 EventCatcher 573–576, 582–583 event-handling logic 548 events simulating 549 test execution 213 AM FL Y 710 Team-Fly® Licensed to Wong Wing Kee INDEX fixtures (continued) as instance-level fields 109 as XML documents 134 changing for each test 128 common services as 90, 304 complex 556 database 340 duplication 84 effect on test readability 86 excessive 683 expensive to set up 161, 164 external data in 346 extracting code into 338, 456 for database tests 346 hierarchy 87 keeping separate 112 large 87 one per entity bean 403 one per method 373 one per Transaction Script 372 one-time setup 158, 161, 170, 249 organizing tests around 20, 73, 92 setup problems 234, 239 shared 106, 164, 249, 332, 346, 557, 559–560, 586, 597, 599 special case tests 18, 92, 372 splitting 73 See also setUp() and tearDown() foreign key 400 foreign key constraints effect on test complexity 334 foreign keys 327 199, 202, 224 formatter type for 199 Fowler, Martin 129, 310, 328, 334, 372, 698 frames 204 framework 234, 259, 501, 519 for unit testing learning process 239 Freeman, Steve 318, 690, 697–698 functional test 110 G Gamma, Eric Gang of Four 215 garbage collection 336, 417–418 garbage-in, garbage-out 304 getDatabaseConnection() 361 getDataSet() 361 getInitParameter() 479 GetMethodWebRequest 454 getName() 178 getPrimaryKey() 410 getProperties() 139 getResourceAsStream() 150–151 getters 41 when to test 42 whether to test 674–675 global data 46, 66, 70, 235 reset between tests 182 global functions session bean methods as 373 going dark 242 Gold Master 323–327, 462, 466, 494 externalizing to file 325 for page templates 457–459, 461, 468, 475, 494 other examples of use 280, 354, 578 when not to use 465 See also Guru Checks Output Golden Master See Gold Master golden results See Gold Master GoldMasterFile 462 good practices 17, 114, 123, 137, 144, 148 Grandma’s Ham 46 graphical user interface 164 green bar 189, 250 GSBase 573, 590, 619–620 assertCollectionsEqual() BaseTestCase 62, 91 EqualsTester 63, 678 See also EqualsTester JDBC resource wrappers 343 OrderedTestSuite 123 RecursiveTestSuite 117, 121, 175 See also RecursiveTestSuite testing equals() 28 See also Base Test Case GUI 106, 164, 399 GUI events 574 Guru Checks Output 326 See also Gold Master H Haggar, Peter 26 Hall, Stephen 697 711 happy path 17, 311, 435 hashCode() 322, 576 consistent with equals() 32 heavyweight 558 Henderson, Anne 699 Hendrickson, Chet 699 here document See herefile herefile 147–148 Hibernate 375–376 HierarchyEvent 575 Highsmith, Jim 699 Hollywood Principle 260 Holser, Paul 284 hot deployment 162 HSQLDB 309, 350 HTML 276, 290 badly-formed 291 form elements 455 ID attribute 301 parsers 291 parsing as XML 290 test results as 189, 202, 205, 215 HTMLConfiguration 295 HtmlPage 494, 522 creating from the file system 491 HTML-tolerant parser 272 HtmlUnit 91, 302, 512–513, 539, 573, 645 broken links 522 defect in version 1.2.3 523 for End-to-End Tests 444, 509 testing EJB security 530 testing static web pages 291 testing web security 526–527 when to use 455 without a web server 491 HTTP 445 HTTP request 455, 496, 498 accessing with ServletUnit 455 parameters 485 processing 483 simulating 486 HTTP response accessing with ServletUnit 455 HTTP session 374, 446, 448–449, 452, 490, 496, 501 interaction 451 HttpClient limitations 523 HttpServletRequest 485, 495, 499, 516 Licensed to Wong Wing Kee 712 INDEX HttpServletRequest.getParameter integrity constraint violation 332 Map() 485 intercept HttpServletResponse 529 method invocations 486 HttpSession 452, 455 interface HttpUnit 91, 444, 454 faking out 67 HttpUtil 516 multiple 53 Hunt, Andrew 42, 697, 699 publishing 48 Husted, Ted 697 testing 48 Hyslop, Jim 699 tests as semantics specification 52 invocation context 455, 499 I isolated tests 106–108, 298, 408, 429, 480 IDE 115–116, 165 problems with 544, 557 effect on organizing See also test isolation source code 78 isolation 509, 545 IDEA 180 impediments to testing in 66 identical testing business logic in 412, 430 XMLUnit 269, 273 testing entity beans in 399 identifier testing in 5, 19, 66 for expected exceptions 57 testing message-driven IDENTITY 349, 351, 362 beans in 426 ignorance testing objects in 387 celebrating 241 testing responsibilities in 434, _ignored 186 484, 495 ignored tests testing session beans in 391 false positives 187 testing web components ignoring tests 107, 185 in 444, 457, 468 implementation pattern testing web pages in 513, 523 testing setter methods 44 isValid() 38, 54 throwing the right IterationTag 469, 473 exception 57 incremental 9, 245 indices 327 J infinite loop 177–178 J2EE 138, 253, 371, 577 info(Object message) use of XML 266 See Log4Unit infrastructure 137, 145, 148, 190 J2EE applications 266, 508, 510 J2EE server 162 inheritance j2ee.jar 413 drawbacks to 193 Jakarta Commons 59, 523 init() Jakarta Commons Logging 198 invoking directly 478 *.jar file InitialContext.lookup() 253 collect tests from 586, 590 initialization 591 and ServletContext 480 Jasper 455, 457, 463 initialization parameters 480 175 277 Java language specification 40 insane object 54 Java logging API 193 INSERT 170 Java system properties 144 installing JUnit 10 Java Virtual Machine 16 integration 509 java.io.tmpdir 142 Integration Tests 79, 123, 137, java.lang.Cloneable 580 162, 625 java.lang.System 139 java.logging 190 java.util.Calendar 54 java.util.Properties 148 java.util.ResourceBundle 152 JavaBeans 38, 44, 54, 457, 469, 581, 583 presentation layer 466 structure of 54 testing 54 96 Javadoc 204 JavaMail 419, 432 JavaServer Pages 272, 444–445, 491, 514, 520 alternatives to 267, 298 and HTTP sessions 455 forwarding from servlet 455 rendering 456–457 tag handler 468 tag library 474 testing data passed to 495 testing in isolation 457 Javassist 185 javax.rmi.Remote 382 jaxen 267 JAXP 223 test failure using 252 JBoss 185, 386, 401, 403, 413, 434, 441, 530, 534 JDBC alternative to 158–159 common trouble spots 321, 333 design criticism 322 duplication in tests 310 for test data 399 problems testing 309 provider 310, 330 reducing dependency on 261, 312, 314, 317 testing queries 317 JDBC client code 408–409 JDBC resources 336, 340, 367 cleaning up 335 effect on test execution 336 in production code 343 JdbcResourceRegistry 340, 362 JDO 386 jEdit 180 Jeffries, Ron 135, 259, 699 Jelly 189 Jetty 495 Licensed to Wong Wing Kee INDEX Jini alternative to EJB 385 jMock 67, 488, 695 JMS 259, 548 JMS exceptions 437 JMS message consumer 376, 420–421, 426, 430–432 JMS message listeners See JMS message consumers JMS message producer 376, 433–434 JMS server 434, 438 JNDI directory 385, 411–412, 414–415, 427, 439–441, 510, 657 as common test resource 593 avoiding 376, 392 in-memory 440 mocking See MockEJB testing contents of 393, 430, 442 JNDI lookups 253, 373, 431, 440 effect on test execution speed 396 testing in isolation 386 JNDI namespace nonglobal 412 jndi.properties 413 JSP engine 457 simulating 468, 470 standalone 463 JSP See JavaServer Pages JspWriter 473 JTidy 296 JUnit alternatives to 675 design philosophy 245 when not to use 322, 366 175, 189, 198–199, 201–202, 224 alternative to 215 custom formatter 214 forking the JVM 181 formatter attribute 209 printsummary attribute 204 using system properties 140 See also JUnit FAQ 253, 255 JUnit Yahoo! group 52, 164, 181, 185, 215, 234, 236, 618 junit.framework 13, 23 junit.framework.AllTests 113 junit.framework.Assert 14 junit.framework AssertionFailedError 15 junit.framework.Test 216 junit.framework.TestCase 13, 240, 395 AllTests pattern 113 junit.framework.TestListener 21 junit.jar 95, 175, 223, 234, 250 junit.log4j.LoggedTestCase 194–195 junit.logswingui.TestRunner 195 junit.runner.TestRunner 215 junit.swingui.TestRunner 174 junit.tests.AllTests 112, 115 junit.textui.TestRunner 11, 174 JUNIT_HOME 175 JUnit-addons 586, 592 assertNotEquals() 31 ComparabilityTestCase 589 ComparableAssert 589 custom assertions 619–620 DirectorySuiteBuilder 119, 175, 590 documentation defect 601 EqualsHashCodeTestCase 32, 64 ignoring tests 186 ResourceManager 593 test runner 176–177, 179, 600 TestClassValidator 614 TestSetup 164, 598 JUnitEE 137 junit-frames.xsl 205 junit-noframes.xsl 205 JUnitPerf 161, 539 JUnitPP 138, 159, 592 default directory 160 176, 189, 202, 204–206, 208–209, 214–215, 224, 596 customizing output 205 junit-frames.xsl 205 junit-noframes.xsl 205 with custom stylesheet 207 JunitResultFormatter 209 JUnitX 248, 480, 604, 620, 622, 626 junitx.extensions.Comparability 713 TestCase 587 junitx.framework.TestProxy 621 junitx.runner.Resource 597 junitx.runner.TestRunner 176 junitx.util.ArchiveSuiteBuilder 590 junitx.util.ResourceManager 593 just for testing 81, 384, 624–625 JVM properties See system properties K Kaner, Cem 698 Kay, Michael 297 keep the test 21, 43 Kerievsky, Joshua 544 key properties 65 L Laflamme, Manuel 170 Langr, Jeff 117 Latkiewicz, George 313, 326, 385, 407, 478 leaking resources 335 learning by writing tests 61 learning curve 234 Learning Test 40, 312, 329, 332, 335, 353, 397, 648 legacy code 108, 323, 357, 389, 422, 626 assertEquals() 581 file system 607, 614 JDBC 341, 349, 357, 359–360 message-driven bean 422, 429 no return value 620 private methods 604, 625 session bean 387 legacy J2EE components 262 Lesiecki, Nicholas 697 lifecycle of JSP tag handlers 468 lightweight container 445, 454 Link, Johannes 697 LinkageError 252 List 24 List.equals() 25 ListAssert 619–620 location in a web application 514 Licensed to Wong Wing Kee 714 INDEX log() overriding in servlets 479 Log4J 190–191, 194, 196, 198, 509 extra logging output 197 Log4Unit 194, 196 default behavior 194 limitations 198 using 194 LoggedTestCase 198 logging 194, 196 configurability 193 how not to use 190 LogKit 190–191 look-and-feel 299 M Mackinnon, Tim 318, 690, 698 Madhwani, Rakesh 164 201 mailto 523 maintenance 348 Manaster, Carl 352 manual tests 322, 483 for EJB security 530 mapping for CMP entity beans 398 Massol, Vincent 697 Maven 189 McConnell, Steve 46 memory testing entirely in 379 Menard, Jason 36 mental model 17 Message 421 message listener 259 instantiating directly 427 message-driven beans 376, 417–418, 427, 430, 432 difficulty testing 420, 426 legacy code 422 testing with MockEJB 423 testing with the container 414 testing without the container 420 MessageDrivenContext 420 MessageListener 426 message-processing logic 427, 429–430 messaging server 438, 478 testing without 426, 434, 438 meta data 397, 404 for CMP entity beans 400 method as a unit to test method invocation intercepting 488–490, 576 recording 549 method invocation sequences recording and verifying 555 verifying with EasyMock 411 Method test name not found 236 Mimer 309, 350 mock data source 368 Mock Objects 312, 318, 325, 344, 357, 473, 672, 690, 694–695 JDBC 357 mock objects 260, 318, 345, 359, 368–369, 386, 392, 409, 426, 430, 432, 518, 568, 649, 681, 689 effect on complexity 319 JDBC 358, 368 JDBC provider 312 JMS 439 overuse 439 mock objects approach 260, 351, 409, 420, 442, 484, 510, 613 MockCallableStatement 367 MockConnection2 368 MockContext 411–412, 438 MockDataSource 412 MockEJB 387, 391, 393, 396, 399, 411–412, 420, 423, 425, 438, 440 supported EJBs 393 MockJspWriter 473 MockMaker 488 MockMultiRowResultSet 318 MockPageContext 471 MockPreparedStatement 313 MockResultSet 321 MockSingleRowResultSet 318 Model 371, 509 Monk, Simon 697 multiple assertions 244 alternatives to 244 motivations for 246 multiple failures 245, 247 for detailed test results 248 multiple test runs 164 multiple tests using same data 106 Multiset See Bag mutable objects 579 MVC See design pattern, Model View Controller MySQL 350 N naming conventions 131, 154, 576 for special case tests 18 for test case classes 18 for test packages 80 for tests 17, 73, 242 naming rules for tests 242 narrow() 254 narrowing EJB references 253 navigation 519 navigation engine 511, 514, 518, 520 navigation rules 371, 509–511, 514, 518–520 modelling 514 testing in isolation 518–519 NekoHTML 291, 294, 302 configuration notes 294 default configuration 295 HTML DOM configuration 294 HTMLConfiguration 294 instantiating parser 295 Xerces compatibility 296 nekohtml.jar 294 network connection 268, 279, 401 network connectivity 279 No test cases found 236 NoClassDefFoundError when executing tests 234 noframes 204 noloading 198 novice programmers 40 null reference 16 nullable 334 nullable columns 327 NullPointerException 479, 499 O object model for HTML 513 Object Tests 5, 10, 335, 414, 470, 474, 556–557, 593 alternatives to 625 Licensed to Wong Wing Kee INDEX Object Tests (continued) and mock objects 690 automated 7–8 different from Test Object 67 for data components 310, 321 for EJBs 414 for J2EE applications 509–510 for legacy code 263 for web components 455, 465, 468, 474, 484, 494 importance of Value Objects 26 object-oriented design 66 organizing code for 79 positive feedback programmer confidence repeatable rhythm of 6, 12 self-verifying 8, 15 test data for 137, 157 Observer 550 one problem at a time 247 one-time setup 165, 249, 521, 597 onMessage() 414 invoking directly 423 open source 6, 194, 245, 290 Open/Closed Principle 613, 689 operating system 165 optimize test suite 162 order of tests 106 controlling 108 JUnit default behavior 109 order-dependent tests 123, 126 example 124 OrderedTestSuite 124–125 as a refactoring tool 125 ordering of objects 586 org.apache.catalina.core StandardWrapper 479 org.custommonkey xmlunit.Diff 274 org.custommonkey.xmlunit DifferenceListener 282 org.dbunit.DatabaseTestCase 170, 361 org.dbunit.dataset.IDataSet 170 org.w3c.dom 217, 223 orthogonality 245 owning the plug 349, 352 P 715 plain-vanilla JVM 413 PMD 241, 616 POJO See Plain Old Java Objects package hierarchy 114 Poppendieck, Mary and Tom 699 page context 470, 473 PostMethodWebRequest 454 page flow 509–510, 513–514 Postscript 209 testing in isolation 511 PreparedStatement 311–312, page templates 267, 514, 520 322, 695 testing data passed to 495 making assertions on 313 Pair Programming 241 presentation engine 267, 272, parameterize 127, 139 304, 465 Parameterized Test Case 65, presentation layer 297, 299, 301, 131–132, 634 304, 374, 499 executing a single test 180 testing without 510 externalizing fixture data 134 for database tests 327, 345, 356 presentation object 371 for J2EE applications 516, 538 Preuß, Ilja 32, 58 prevalent system See Prevayler for JNDI directories 442 for web components 473, 506 Prevayler 375, 509, 607 primary key 408–409 problem with Cactus 442 primitive values using XML 134–135, 630 comparing 23 Parameterized tests printf 20, 330 See Parameterized Test Case printsummary 201, 204 parameterizing private data test data 137 gaining access to 622 277 private methods 480, 604, 625, 627 277 testing 81 passivation 393 PrivateTestCase 621 PDF 209 problems test results as 205 common 234 performance 147, 259, 336, procedure 372–373 419, 464, 525 production code problem with containers 259 shipping tests with 590 permissions 356 productivity 224 database objects 352 Programmer Test suites 111 persistence 376, 386, 388, 408 Programmer Testing 4–5, 41, 66, pluggable 375 309, 396, 607 Pettichord, Bret 698 goals of 334 philosophy 107 good practices 106 Plain Old Java Objects 379, Programmer Tests 110, 120, 386, 424, 432 464, 509 and equals() 287 relationship to Customer and lightweight Tests 111 frameworks 386 simplest 23 examples 664, 669 progress 224 extracting from EJBs 373, properties 138, 148, 152, 156, 379, 421 325, 591 extracting from JMS built-in 142 components 431 for test data 138 refactoring Singleton Java system 139 into 558, 560 reading from file 149 setting 139 with web components 490 Licensed to Wong Wing Kee 716 INDEX Extract Method 619 fixtures 88, 304 into a Base Test Case 337 Move Method 379 Replace Subclass with Collaborator 490 tests 159, 341, 604 tests as safety net 70, 259, 334, 349 tests as safety net See safety net to methods instead of constants 325 Q towards a Parameterized Test Case 345 queries 311 towards a testable design query expressions 309–310, 379, 430, 452 for XML 266 towards design patterns 544 query method towards test isolation 123, 125 add for testing 36 without tests 419, 422, 561 quick green 383 referential integrity 406, 597 arguments for 407 R overuse 400 reflection 105, 131, 243 rathole 365 to invoke test method 109 readability 158 registerServlet() 455 readable properties 24 regression testing a class without 38–39 test 330 recompiling relational data avoiding 139 converting to objects 317 RecursiveTestSuite 117–118, ReloadedTestCaseDecorator 120–121, 175, 590 183, 185 compared to remote connection DirectorySuiteBuilder 119 eliminating from tests 280 parameters to 117 remote method invocation 577 red bar 250 202, 205 reducing dependency 260 defect in 207 refactor 19, 302, 337 styledir attribute 205 unable to 389 using frames 204 when you cannot 377 reporting test results 16, 189 refactoring 9, 75, 181–182, 444 reports and coupling 19, 80 custom format 189, 205 and legacy code 360, 389 customizing 205 assertions 302 format of 189 away from containers 259 request 446 away from the database 312, request dispatcher 490, 518 334, 357 request handler effect on AllTests 115 behavior of 518 EJBs 376, 395, 408, 413, 430 resetFixture() 126 Extract Class 507 resource references 412 properties file 147, 164 location in source tree 151 managing multiple 592 test data as 586 PropertyManager 586, 591 limitations 592 protected methods 76, 604 public interface testing entirely through 37 publisher See design pattern, Observable ResourceBundle 138, 151–153, 164 ResourceBundle.getBundle (String baseName) 153 ResourceManager 586, 596 ResourceManagerTestSetup 596 resources order of initialization 597 ResourceTestSetup 593 responsibilities separating 548, 550 result in a web application 514 result sets 330 cleaning up 335 ResultPrinter 545 ResultSet 311, 318, 322, 345 creating domain objects from 317 hardcoded 319 mapping data from 319 ResultSetMetaData 331 return on investment 38 testing setter methods 48 return value 23, 26 legacy method without 620 method without 414, 484, 545 testing a method with 23 testing a method without one 33 XML document as 266 revealing intent 17, 55, 59, 75, 128, 403 rhythm of a test 105 of an Object Test rich client 374 ripple effect 111, 556 RMI See remote method invocation Ruby 59 rules 56 runBare() 86, 243 runSuite() 215 runTest() 109, 179, 241 alternatives to overriding 242 invoking multiple test methods 242 overriding 132, 234, 241–242, 570, 634 RuntimeException 16, 59 Licensed to Wong Wing Kee INDEX S extracting business logic from 444 safety net 7, 108, 125, 182, 334, forwarding to JSP 455 511, 625–626, 675 initialization 454, 477 and legacy code 349, 422 initialization parameters 277, 287 benefits of 259 legacy code 263, 452 changing code without 561 multiple 481 false sense of security 78 passing data to web pages 496 refactoring without 70, 419 processing requests 483, 486 using Cruise Control 398 redeploying 162 See also refactoring, request attributes 277 tests as safety net session attributes 277 sanity check 54 session data 446, 449, 455–456 scenario 372 specification 277 schema-qualified tables 363 typical behavior 483 scripting 189 ServletTestCase 395, 441 variable 469 ServletUnit 444–445, 455–456, ScriptIt 166 460, 488, 495, 499 security 386, 395, 398, 509–510, and HTTP session 453 527, 529, 532–533 for legacy code 448, 455 EJB 530 note on Invocationprogrammatic 409 Context 456 web resource 525 testing filters 505 security server 478 testing J2EE applications 518 SecurityException 533–534 testing ServletContext 481 SELECT 317 URL mapping 456 self-documenting 9, 15 when to use 456, 498 sense of completion 114 with Jasper 457 sequence diagram 421, 427 ServletUnitClient 455 sequence difference session in XML documents 281 design issues 446 serial version UID 578 reducing interaction with 451 SerializabilityTest 573 session bean 372, 384, 394, Serializable 382 396, 440 serialization 573, 577 delegating to domain server-side tests 394 object 379 service() 455–456 relationship to entity services beans 399 as plug-ins 261 stateful 374, 446 servlet session testing implementation accessing with ServletUnit 453 directly 385 ServletConfig 479 testing methods ServletContext 480–481, 483 independently 372 ServletRunner 445, 454, 499 testing outside the servlets 259, 444–445, 451, 484, container 378 494, 507, 513, 518, 613, 637 session data 446, 452 and filters 500 and XSL transformations 304 set method difficulties testing 45 design problems 259 See also setters executing server-side setEntityContext() 411 tests 396, 442 717 setExpectedCloseCalls() 345 setters 44 whether to test 674–675 setUp() 84–86, 148–149, 158, 170, 178, 191, 239, 242, 272, 287, 337, 340, 347, 363, 403, 483, 488, 528, 532, 567, 600, 605, 687 incorrectly overriding 614 invoking super.setUp() 88, 239 log messages 196 once per test suite 161 one-time 162 typo 239 shared fixture effect on test isolation 106 shared test fixture as a design issue 599 shared test setup 346 side effect 35, 484, 545, 549 invisible 36, 478, 546 observable 34–36, 38, 45, 548, 620, 625, 649 similar XMLUnit 269, 273 SimpleCredentialProvider 527 simplifying interface 434 simulate 392, 526, 529, 690 error conditions 69 simulator for web container 454 Single Responsibility Principle 81, 548, 555, 608 Singleton wise usage 46, 67 Smalltalk 6, 15, 59, 61, 117, 324, 397 SMTP 415 SMTP server 419 source code difficult to navigate 111 source control 155 source trees 77 special case tests 18 Specification by Example 65 specifications 5, 392, 468 and third-party software 471 spreadsheets tests as 509 Spring 386 spy 46, 425 event listener 82 Licensed to Wong Wing Kee 718 INDEX SQL 158 parsers for Java 309 query validator 309 verifying commands 322 157 SQL commands manual tests for 322 state diagram 510 stateless session beans ease of testing 373 statements cleaning up 335 static web page 457 Stobie, Keith 327 stored procedures 158, 355, 366–368 deployment tests 352 testing without JUnit 366 StringAssert 620 StringReader 145 Struts 246, 278, 302–303, 495, 510–511, 518–522, 639 testing without 519 struts-config.xml 302, 518–519, 521 StrutsTestCase 510 stub 690–691 stub method 67 stultifyingly abstract 64 206 style-checking software 240 stylesheets 204–206 subclassing alternatives to 193 class under test 503 subscriber See design pattern, Observer Subversion 121 suite of suites 109, 112, 114–115 suite() 104, 108, 113, 115, 123– 124, 128–129, 134, 162, 164, 174, 184, 191, 237–238, 442, 596, 634 default behavior 105 duplication in 110 forgetting to update 104 ignoring 112 incorrectly coding 614 invoking explicitly 238 SuiteBuilder 586 SUnit 6, 397 Swing 374, 573–574 Swingler, Neil 183 syntax 604 140–141 system properties 138, 141, 148, 153, 155, 160 managing 591 omitting from reports 206 setting test data 140 System.getProperty() 143 System.out 189, 194, 197 one per production class 93, 373 order of tests 123 syntax of 614 test data 127, 132, 137–138, 155, 157, 349, 362, 389, 396, 398, 409, 591, 612, 630, 634, 657, 684 alternatives to XML 157 centralizing 592 command line arguments 138–139 database 157, 346 describing with XML 156 T entity bean commit options 399 tablespace 350 excessive 400 tag handler 468, 474 externalize 103, 148, 152, 158 tag interface externalizing 132 for classifying tests 121 file-based repository 154 tag library 477 for database 360 tag library descriptors 475, 477 formats 156 TDD See Test-Driven generating 137 Development global 142, 166, 169, 181–182 team environment 190, 204 hardcoded 139, 148, 157, 460 tearDown() 85, 158, 170, 191, 239, hierarchical 138 242, 337–338, 340, 347–348, in files 145 567, 597, 599, 605, 607, 687 in multiple files 152 and fixture setup errors 598 in properties files 591 incorrectly overriding 614 initialize once per JVM 168 invoking super.tearDown() JUnit-addons test runner 177 89, 239 large amounts 154 log messages 196 locating within tests 155 once per test suite 161 naming conventions one-time 162 for files 156 typo 239 organizing 156 Telnet 199 organizing in source control 156 temporary files 142 parameterized 148 temporary test suite properties files 159 when fixing a defect 110 resetting between tests 170 199 resetting global state 181 test case restoring between tests 171 performance problems 162 restoring to initial state 138, 158 reloading classes 183 setup complexity 360 test case classes shared 137 correspondence to shared repository 154 production class 373 small amounts 139, 141 each test is an instance 109 static 138 handling multiple 111 system properties 138 inheriting tests 107 tabular 356 large 18 under version control 155 many in one package 111 using JDBC 362 naming convention 117 Licensed to Wong Wing Kee INDEX test database 312, 349, 360 sharing 349 test environment 498 as a tool 165 auditing 190 automating 166 complex 393, 413, 548, 611 complexity 396 one-button 166 one-time setup 168 test file 142 test fixture 106, 131, 236, 239, 249, 346, 445, 483 complex 597 extracting 133 extracting data into 128 hierarchy 239 naming 18 setup problems 239 test hierarchies behavior in JUnit 52 Test Infected 104, 108 test isolation 108–109, 480, 544, 557, 563, 605, 614, 625 effect of databases 334, 346 effect of shared fixtures 346, 597, 605, 608 effect of Singleton 559 effect of Singletons 556, 560 refactoring towards 123, 125 test listener open architecture 586 See also TestListener test management system 205 test methods coding errors 235 execute in its own JVM 181 mistyped name in suite() method 236 naming convention 104 naming guidelines 236 not found 235 similar 127 throwing exceptions 105 Test Object 67 Test Objects 67, 390–391, 412, 426, 488, 559, 695 crash test dummy 69 fake 67 mock 67 simulating error conditions 69 stub 67 substituting 69 test package hierarchy 80 test reports customizing 586 test resources shared 586, 593 test results 217 as HTML 202 auditing 190 custom format 208 customized 224 customizing 190, 215 in XML 223 logging 190 management system 209 plain text 198 sending in email 201 test runner 8, 11, 111, 174, 220 AWT-based 174 built-in 189 class path problem 235 class-loading problems 250 custom 167, 174, 194, 586 extending 224 JUnit-addons 176, 187, 596, 602 launching 174 Log4Unit 197 problems with EJBs 254 specifying test data files 148 status bar 177 Swing-based 167, 174, 178 terminate() 168 text-based 11, 141, 166, 174, 178, 195, 215, 599 test suite 8, 103, 398, 586, 607, 630 arbitrarily complex 103 arbitrary collection of tests 111 as XML document 133 build automatically 103, 105 build from file system 116 build manually 104, 108 builder 117 building a bigger one 109 building manually 104 collecting tests into 103 create from a package 111 custom 236, 249 data-driven 127 default 105, 107, 236 719 define using XML 157 executing repeatedly 169 extract automatically 112 for the entire system 114 how JUnit executes 109 maintenance issues 116 managing 103 manual 184 not executed 237 portable 138 test order 103 test until fear turns to boredom 38, 56, 406, 676 testability 36 testable design 74, 82, 108, 259, 385, 608, 620, 626 effect of class-level methods 70 refactoring towards 309, 378, 422 TestCase 12, 18, 189, 225 difference between class and instance 242 executing only one 180 extending 190 extension 194 inheritance rules 52 TestCase class one per production class 72 TestCase hierarchy 73 TestCaseClassLoader 254 TestClassValidator 614, 616 testClone() 579–580 Test-Driven Development 9, 87, 137, 185, 245, 250, 406, 573, 691 and Exploratory Testing and legacy code 125 and organizing code 74, 79 and test isolation 106, 108 effect on design 70, 82, 91, 378 example of 547 fixing defects 110 TestFilter 117–118, 120–121 ignore abstract tests 118 testing effect of referential integrity constraints 400 manual only for 36–37, 418, 558 the goal of 675 testing department testing methods together 35 Licensed to Wong Wing Kee INDEX TESTS-TestSuites.xml 207 TestSuite 105, 108, 133, 525 text node with empty content 271 TextUtil 493 third-party library See external library Thomas, Dave 42, 697, 699 Thread.sleep() 417 throwing the right exception how not to test 58 throws Exception declaring test methods 57 Tidy 291, 296 tolerance level for floating-point numbers 14 Tomcat 463, 479 too simple to break 39, 41, 43–44, 55, 379, 384, 410, 421, 451, 562, 674 rebuttal 677 Torque 376 Transaction Script 372 transactions 380, 386, 398–399, 427, 509–510, 662 attributes 536, 538 behavior 348 container-managed 536, 538 isolation 539 isolation level 536 rollback trick 347 Transform 300 transitivity property of equals() 677 triggers 327 trusted libraries 312 201 typing, too much 24 typo 604 TE Testing Patterns Abstract Test Case 52, 544, 587 AllTests 112, 114 Crash Test Dummy 399, 429, 569, 672, 693 fixture barrier 126 Isolated Test 106 Log String 567, 649 one failure per problem 107 Parameterized Test Case 128, 241, 243, 506, 516, 538, 630 Self-Shunt 184, 389–391, 425– 432, 545, 550–555, 623, 693 Spy 422–432, 507, 552, 563, 567, 574, 626, 649, 688, 693 testing, only for 419, 618 TestListener 215, 232, 545, 552, 555, 596, 602 event handlers 216 TestProxy 623 TestResult 249, 552, 554–555 TestRunListener 600 TestRunner as a listener 215 extending 215, 220 JUnit-addons 600 tests annotated 509 as specification 36 categorizing 103 cost of executing 464 deploying 590 execution speed 259 general form of 25 JUnit cannot find 104, 235 JUnit not executing 104 long-running 190 manual order of 123 order-dependent 249 problems implementing 234 seemingly too simple 41 too simple to write 38 written by nonprogrammers 510 testSerialization() 577–578 TestSetup 138, 161–162, 164, 170, 521, 586, 593, 599 effect on fixture implementation 164 JUnit-addons implementation 598 tearDown problems 164 UnsupportedOperation Exception 32 upgrade 252 useless tests 40 user.home 142, 155 V validation testing in constructor 39 Value Object 26–27, 32, 311, 321, 575–576, 578, 581, 617, 678 as XML document 268 primitive wrapper classes 27 with many properties 63 ValueObjectEqualsTest 64 Vector 382 Velocity 246, 272, 371, 444–445, 465, 491, 493–494, 499, 514, 520 public fields 467 rendering template 465, 467 standalone mode 467 testing data passed to 495 VelocityContext 466 verify() 411, 694–695 version control 253 View 371, 496 Virtual Mock 70, 561 Virtual Mock Objects 263 visual inspection 299, 461, 494, 496, 498 VisualAge for Java effect on test packages 82 void See return value AM FL Y 720 U unchecked exception 437 unexpected state after failed test 106 uniqueness constraints 333 unit testing 4, 137 UNIX 274 UnknownHostException thrown by XMLUnit 279 unpacking JUnit 10 unpredictable state for future tests 107 W Wake, Bill 6, 23 web applications 246, 267, 272, 291, 293, 303, 444, 483–484, 513, 522, 533 deploying tests for 395 designing for testability 376, 500–501 presentation layers 297 testing components in isolation 446, 448, 505, 509–510 testing navigation rules 509–510, 519 web deployment descriptors 278, 481 See also deployment descriptors Team-Fly® Licensed to Wong Wing Kee INDEX web browser 290 simulating 291 web components 444, 474, 495 web container 399, 444–445, 468, 479, 483, 505 avoiding 445, 484 for processing JSPs 464 simulating 445, 455 testing interaction with 456 testing with 445 web deployment descriptor 277– 280, 287, 303, 527, 532, 637 generating 280 web forms 494, 523 web page content 491 web page templates 291 web pages 267, 296, 299, 301, 448, 514 comparing 301 dynamic 291, 493 static 290–291, 493 testing in isolation 272 web request 513 web resource 530 web resource filter 500, 507 responsibilities 500 web server 165 testing web page without 491 testing without 491 web services 267–268 Web Services Description Language 266 web.xml See web deployment descriptor web-authoring tools compatibility with 294 WebClient 522, 527–528 WebRequest 454, 499 Weinberg, Gerald 699 well-factored 135 well-factored design See refactoring Wenner, Robert 616 what not to test 55 white space 273 in XML documents 270–271 white space only elements and XMLUnit 272 Wiki 510 Woolley, Chad 70 wrapper classes for primitive types 27 wrappers 372, 385, 421, 490 See also design pattern, Decorator 721 XMLUnit 269, 401, 464, 477, 495, 519, 530, 537, 619, 639 and DTDs 477 assertXMLEqual() 273, 276 buildXmlDocument() 279 X detailed failure message 288 diff 275 Xalan 208, 267, 297 Diff engine 281, 288 XDoclet 538 Xerces 223, 294, 297, 648 example test 270 XHTML 266, 272, 290, 296 failure message 271 scarcity of 290 for EJB meta data 375 tag name standards 296 for J2EE deployment XJavaDoc 538 descriptors 401, 505, 535 XML 145, 148, 155–156, 215, for JavaServer Pages 464 217, 220, 266, 401, 403, 475, for JSP custom tags 475 535, 587, 630 for Struts applications 519 causes JUnit failures 252 for XSL transformations 298, 301 comparing documents 267, identical documents 273, 275 270, 280 ignoring differences 272, 282 defining test suites with 133 ignoring white space 271 object marshalling 267, 273 limitations of 278 order of elements 273 order of sibling elements 276 storing test data 138 org.custommoney test results as 189 xmlunit.Diff 274 well-formed 291 parsing 279, 639 XML documents 519, 637 with HTML documents 292 as a return value 266 See also XMLTestCase element structure 270 XPath 266, 287, 293, 328, 403, for configuration 303 475, 521, 538, 639 for data transfer 303 API 267, 278 hardcode in tests 298 assertions using 266 ignoring differences 287 XSL 204–206, 209 ignoring the order of XSL stylesheet 298, 301, 639, 645 elements 277 testing in isolation 297 listing all differences 289 XSL transformation 266–267, making assertions on 269 297–298, 304, 645 problems with line breaks 270 alternative to JSPs 297 testing without files 268 as presentation layer 282 to describe a database 328 testing in isolation 272 unexpectedly equal 275 validating 272, 477, 519, 537, 645 XSLT 272, 304 See also XSL transformation validating in tests 302 xUnit 6, 61 validating incoming data 304 walking the DOM 278 Y writing assertions for 521 XML parsers 266 YAGNI 91 XML parsing 147, 279 XML schema 272, 303–304 avoiding overuse 306 Z XMLJUnitResultFormatter 214 XMLTestCase 267, 401, 619 ZipFile 590 Licensed to Wong Wing Kee JAVA J B Rainsberger with contributions by Scott Stirling W hen testing becomes a developer’s habit good things tend to happen—good productivity, good code, and good job satisfaction If you want some of that, there’s no better way to start your testing habit, nor to continue feeding it, than with JUnit Recipes In this book you will find one hundred and thirty seven solutions to a range of problems, from simple to complex, selected for you by an experienced developer and master tester Each recipe follows the same organization giving you the problem and its background before discussing your options in solving it JUnit—the unit testing framework for Java—is simple to use, but some code can be tricky to test When you’re facing such code you will be glad to have this book It is a how-to reference full of practical advice on all issues of testing, from how to name your test case classes to how to test complicated J2EE applications Its valuable advice includes side matters that can have a big payoff, like how to organize your test data or how to manage expensive test resources What’s Inside ■ Getting started with JUnit ■ Recipes for servlets, JSPs, EJBs, Database code, and much more ■ Difficult-to-test designs, and how to fix them ■ How testing saves time ■ Choosing a JUnit extension: HTMLUnit, XMLUnit, ServletUnit, EasyMock, and more! J B Rainsberger is a developer and consultant who has been a leader in the JUnit community since 2001 His popular online tutorial JUnit: A Starter Guide is read by thousands of new JUnit users each month Joe lives in Toronto, Canada “Educational writing, a reference manual with working examples, and a compelling argument for how testing can increase productivity and quality.” —Michael Rabbior, IBM “I like the ‘been there, done that, don't it please’ approach J B has the experience and explains the why of the solutions.” —Vladimir Ritz Bossicard JUnit Development Team “I'm finding this book to be a useful ‘pattern reference’ —it will have stuff to mine for years to come ” —Eric Armstrong author of JBuilder2 Bible consultant for Sun Computing “Wonderful just publish it so I can make it required reading for my team!” —Simon Chappell, Lands End AUTHOR ✔ JUnit Recipes Practical Methods for Programmer Testing ✔ ONLINE Ask the Author Ebook edition www.manning.com/rainsberger ,!7IB9D2-djecdi!:p;O;T;t;p MANNING $49.95 US/$69.95 Canada ISBN 1-932394-23-0 .. .JUnit Recipes JUnit Recipes Practical Methods for Programmer Testing J.B RAINSBERGER with contributions by SCOTT STIRLING MANNING Greenwich (74° w long.) Licensed... rather be Programmer Testing.” 1.1 What is Programmer Testing? Programmer Testing is not about testing programmers, but rather about programmers performing tests In recent years some programmers... in time For online information and ordering of this and other Manning books, please visit www .manning. com The publisher offers discounts on this book when ordered in quantity For more information,