forked from spring-projects/spring-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesting.xml
More file actions
3708 lines (3116 loc) · 177 KB
/
testing.xml
File metadata and controls
3708 lines (3116 loc) · 177 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<chapter version="5.0"
xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd"
xml:id="testing" xmlns="http://docbook.org/ns/docbook"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:ns2="http://www.w3.org/1998/Math/MathML"
xmlns:ns="http://docbook.org/ns/docbook">
<title>Testing</title>
<section xml:id="testing-introduction">
<title>Introduction to Spring Testing</title>
<para>Testing is an integral part of enterprise software development. This
chapter focuses on the value-add of the IoC principle to <link
linkend="unit-testing">unit testing</link> and on the benefits of the Spring
Framework's support for <link linkend="integration-testing">integration
testing</link>. <emphasis>(A thorough treatment of testing in the enterprise
is beyond the scope of this reference manual.)</emphasis></para>
</section>
<section xml:id="unit-testing">
<title>Unit Testing</title>
<para>Dependency Injection should make your code less dependent on the
container than it would be with traditional Java EE development. The POJOs
that make up your application should be testable in JUnit or TestNG tests,
with objects simply instantiated using the <literal>new</literal> operator,
<emphasis>without Spring or any other container</emphasis>. You can use
<link linkend="mock-objects">mock objects</link> (in conjunction with other
valuable testing techniques) to test your code in isolation. If you follow
the architecture recommendations for Spring, the resulting clean layering
and componentization of your codebase will facilitate easier unit testing.
For example, you can test service layer objects by stubbing or mocking DAO
or Repository interfaces, without needing to access persistent data while
running unit tests.</para>
<para>True unit tests typically run extremely quickly, as there is no
runtime infrastructure to set up. Emphasizing true unit tests as part of
your development methodology will boost your productivity. You may not need
this section of the testing chapter to help you write effective unit tests
for your IoC-based applications. For certain unit testing scenarios,
however, the Spring Framework provides the following mock objects and
testing support classes.</para>
<section xml:id="mock-objects">
<title>Mock Objects</title>
<section xml:id="mock-objects-env">
<title>Environment</title>
<para>The <literal>org.springframework.mock.env</literal> package
contains mock implementations of the
<interfacename>Environment</interfacename> and
<interfacename>PropertySource</interfacename> abstractions introduced in
Spring 3.1 (see <xref linkend="new-in-3.1-environment-abstraction"/> and
<xref linkend="new-in-3.1-property-source-abstraction"/>).
<classname>MockEnvironment</classname> and
<classname>MockPropertySource</classname> are useful for developing
<emphasis>out-of-container</emphasis> tests for code that depends on
environment-specific properties.</para>
</section>
<section xml:id="mock-objects-jndi">
<title>JNDI</title>
<para>The <literal>org.springframework.mock.jndi</literal> package
contains an implementation of the JNDI SPI, which you can use to set up
a simple JNDI environment for test suites or stand-alone applications.
If, for example, JDBC <classname>DataSource</classname>s get bound to
the same JNDI names in test code as within a Java EE container, you can
reuse both application code and configuration in testing scenarios
without modification.</para>
</section>
<section xml:id="mock-objects-servlet">
<title>Servlet API</title>
<para>The <literal>org.springframework.mock.web</literal> package
contains a comprehensive set of Servlet API mock objects, targeted at
usage with Spring's Web MVC framework, which are useful for testing web
contexts and controllers. These mock objects are generally more
convenient to use than dynamic mock objects such as <link
xl:href="http://www.easymock.org">EasyMock</link> or existing Servlet
API mock objects such as <link
xl:href="http://www.mockobjects.com">MockObjects</link>.</para>
</section>
<section xml:id="mock-objects-portlet">
<title>Portlet API</title>
<para>The <literal>org.springframework.mock.web.portlet</literal>
package contains a set of Portlet API mock objects, targeted at usage
with Spring's Portlet MVC framework.</para>
</section>
</section>
<section xml:id="unit-testing-support-classes">
<title>Unit Testing support Classes</title>
<section xml:id="unit-testing-utilities">
<title>General utilities</title>
<para>The <literal>org.springframework.test.util</literal> package
contains <classname>ReflectionTestUtils</classname>, which is a
collection of reflection-based utility methods. Developers use these
methods in unit and integration testing scenarios in which they need to
set a non-<literal>public</literal> field or invoke a
non-<literal>public</literal> setter method when testing application
code involving, for example:</para>
<itemizedlist>
<listitem>
<para>ORM frameworks such as JPA and Hibernate that condone
<literal>private</literal> or <literal>protected</literal> field
access as opposed to <literal>public</literal> setter methods for
properties in a domain entity.</para>
</listitem>
<listitem>
<para>Spring's support for annotations such as
<interfacename>@Autowired</interfacename>,
<interfacename>@Inject</interfacename>, and
<interfacename>@Resource,</interfacename> which provides dependency
injection for <literal>private</literal> or
<literal>protected</literal> fields, setter methods, and
configuration methods.</para>
</listitem>
</itemizedlist>
</section>
<section xml:id="unit-testing-spring-mvc">
<title>Spring MVC</title>
<para>The <literal>org.springframework.test.web</literal> package
contains <classname>ModelAndViewAssert</classname>, which you can use in
combination with JUnit, TestNG, or any other testing framework for unit
tests dealing with Spring MVC <classname>ModelAndView</classname>
objects.</para>
<tip>
<title>Unit testing Spring MVC Controllers</title>
<para>To test your Spring MVC <literal>Controller</literal>s, use
<classname>ModelAndViewAssert</classname> combined with
<literal>MockHttpServletRequest</literal>,
<literal>MockHttpSession</literal>, and so on from the <link
linkend="mock-objects-servlet">
<literal>org.springframework.mock.web</literal></link> package.</para>
</tip>
</section>
</section>
</section>
<section xml:id="integration-testing">
<title>Integration Testing</title>
<section xml:id="integration-testing-overview">
<title>Overview</title>
<para>It is important to be able to perform some integration testing
without requiring deployment to your application server or connecting to
other enterprise infrastructure. This will enable you to test things such
as:</para>
<itemizedlist>
<listitem>
<para>The correct wiring of your Spring IoC container contexts.</para>
</listitem>
<listitem>
<para>Data access using JDBC or an ORM tool. This would include such
things as the correctness of SQL statements, Hibernate queries, JPA
entity mappings, etc.</para>
</listitem>
</itemizedlist>
<para>The Spring Framework provides first-class support for integration
testing in the <filename class="libraryfile">spring-test</filename>
module. The name of the actual JAR file might include the release version
and might also be in the long
<filename>org.springframework.test</filename> form, depending on where you
get it from (see the <link linkend="dependency-management">section on
Dependency Management</link> for an explanation). This library includes
the <literal>org.springframework.test</literal> package, which contains
valuable classes for integration testing with a Spring container. This
testing does not rely on an application server or other deployment
environment. Such tests are slower to run than unit tests but much faster
than the equivalent Cactus tests or remote tests that rely on deployment
to an application server.</para>
<para>In Spring 2.5 and later, unit and integration testing support is
provided in the form of the annotation-driven <link
linkend="testcontext-framework">Spring TestContext Framework</link>. The
TestContext framework is agnostic of the actual testing framework in use,
thus allowing instrumentation of tests in various environments including
JUnit, TestNG, and so on.</para>
</section>
<section xml:id="integration-testing-goals">
<title>Goals of Integration Testing</title>
<para>Spring's integration testing support has the following primary
goals:</para>
<itemizedlist>
<listitem>
<para>To manage <link linkend="testing-ctx-management">Spring IoC
container caching</link> between test execution.</para>
</listitem>
<listitem>
<para>To provide <link linkend="testing-fixture-di">Dependency
Injection of test fixture instances</link>.</para>
</listitem>
<listitem>
<para>To provide <link linkend="testing-tx">transaction
management</link> appropriate to integration testing.</para>
</listitem>
<listitem>
<para>To supply <link
linkend="testing-support-classes">Spring-specific base classes</link>
that assist developers in writing integration tests.</para>
</listitem>
</itemizedlist>
<para>The next few sections describe each goal and provide links to
implementation and configuration details.</para>
<section xml:id="testing-ctx-management">
<title>Context management and caching</title>
<para>The Spring TestContext Framework provides consistent loading of
Spring <classname>ApplicationContext</classname>s and
<classname>WebApplicationContext</classname>s as well as caching of
those contexts. Support for the caching of loaded contexts is important,
because startup time can become an issue — not because of the overhead
of Spring itself, but because the objects instantiated by the Spring
container take time to instantiate. For example, a project with 50 to
100 Hibernate mapping files might take 10 to 20 seconds to load the
mapping files, and incurring that cost before running every test in
every test fixture leads to slower overall test runs that reduce
developer productivity.</para>
<para>Test classes typically declare either an array of
<emphasis>resource locations</emphasis> for XML configuration metadata —
often in the classpath — or an array of <emphasis>annotated
classes</emphasis> that is used to configure the application. These
locations or classes are the same as or similar to those specified in
<literal>web.xml</literal> or other deployment configuration
files.</para>
<para>By default, once loaded, the configured
<interfacename>ApplicationContext</interfacename> is reused for each
test. Thus the setup cost is incurred only once per test suite, and
subsequent test execution is much faster. In this context, the term
<emphasis>test suite</emphasis> means all tests run in the same JVM —
for example, all tests run from an Ant, Maven, or Gradle build for a
given project or module. In the unlikely case that a test corrupts the
application context and requires reloading — for example, by modifying a
bean definition or the state of an application object — the TestContext
framework can be configured to reload the configuration and rebuild the
application context before executing the next test.</para>
<para>See <xref linkend="testcontext-ctx-management"/> and <xref
linkend="testcontext-ctx-management-caching"/> with the TestContext
framework.</para>
</section>
<section xml:id="testing-fixture-di">
<title>Dependency Injection of test fixtures</title>
<para>When the TestContext framework loads your application context, it
can optionally configure instances of your test classes via Dependency
Injection. This provides a convenient mechanism for setting up test
fixtures using preconfigured beans from your application context. A
strong benefit here is that you can reuse application contexts across
various testing scenarios (e.g., for configuring Spring-managed object
graphs, transactional proxies, <classname>DataSource</classname>s,
etc.), thus avoiding the need to duplicate complex test fixture setup
for individual test cases.</para>
<para>As an example, consider the scenario where we have a class,
<classname>HibernateTitleRepository</classname>, that implements data
access logic for a <classname>Title</classname> domain entity. We want
to write integration tests that test the following areas:</para>
<itemizedlist>
<listitem>
<para>The Spring configuration: basically, is everything related to
the configuration of the
<classname>HibernateTitleRepository</classname> bean correct and
present?</para>
</listitem>
<listitem>
<para>The Hibernate mapping file configuration: is everything mapped
correctly, and are the correct lazy-loading settings in
place?</para>
</listitem>
<listitem>
<para>The logic of the
<classname>HibernateTitleRepository</classname>: does the configured
instance of this class perform as anticipated?</para>
</listitem>
</itemizedlist>
<para>See dependency injection of test fixtures with the <link
linkend="testcontext-fixture-di">TestContext framework</link>.</para>
</section>
<section xml:id="testing-tx">
<title>Transaction management</title>
<para>One common issue in tests that access a real database is their
effect on the state of the persistence store. Even when you're using a
development database, changes to the state may affect future tests.
Also, many operations — such as inserting or modifying persistent data —
cannot be performed (or verified) outside a transaction.</para>
<para>The TestContext framework addresses this issue. By default, the
framework will create and roll back a transaction for each test. You
simply write code that can assume the existence of a transaction. If you
call transactionally proxied objects in your tests, they will behave
correctly, according to their configured transactional semantics. In
addition, if a test method deletes the contents of selected tables while
running within the transaction managed for the test, the transaction
will roll back by default, and the database will return to its state
prior to execution of the test. Transactional support is provided to a
test via a <classname>PlatformTransactionManager</classname> bean
defined in the test's application context.</para>
<para>If you want a transaction to commit — unusual, but occasionally
useful when you want a particular test to populate or modify the
database — the TestContext framework can be instructed to cause the
transaction to commit instead of roll back via the <link
linkend="integration-testing-annotations"><interfacename>@TransactionConfiguration</interfacename></link>
and <link
linkend="integration-testing-annotations"><interfacename>@Rollback</interfacename></link>
annotations.</para>
<para>See transaction management with the <link
linkend="testcontext-tx">TestContext framework</link>.</para>
</section>
<section xml:id="testing-support-classes">
<title>Support classes for integration testing</title>
<para>The Spring TestContext Framework provides several
<literal>abstract</literal> support classes that simplify the writing of
integration tests. These base test classes provide well-defined hooks
into the testing framework as well as convenient instance variables and
methods, which enable you to access:</para>
<itemizedlist>
<listitem>
<para>The <literal>ApplicationContext</literal>, for performing
explicit bean lookups or testing the state of the context as a
whole.</para>
</listitem>
<listitem>
<para>A <classname>JdbcTemplate</classname>, for executing SQL
statements to query the database. Such queries can be used to
confirm database state both <emphasis>prior to</emphasis> and
<emphasis>after</emphasis> execution of database-related application
code, and Spring ensures that such queries run in the scope of the
same transaction as the application code. When used in conjunction
with an ORM tool, be sure to avoid <link
linkend="testcontext-tx-false-positives">false
positives</link>.</para>
</listitem>
</itemizedlist>
<para>In addition, you may want to create your own custom,
application-wide superclass with instance variables and methods specific
to your project.</para>
<para>See support classes for the <link
linkend="testcontext-support-classes">TestContext
framework</link>.</para>
</section>
</section>
<section xml:id="integration-testing-support-jdbc">
<title>JDBC Testing Support</title>
<para>The <literal>org.springframework.test.jdbc</literal> package
contains <classname>JdbcTestUtils</classname>, which is a collection of
JDBC related utility functions intended to simplify standard database
testing scenarios. <emphasis>Note that <link
linkend="testcontext-support-classes-junit4"><classname>AbstractTransactionalJUnit4SpringContextTests</classname></link>
and <link
linkend="testcontext-support-classes-testng"><classname>AbstractTransactionalTestNGSpringContextTests</classname></link>
provide convenience methods which delegate to
<classname>JdbcTestUtils</classname> internally.</emphasis></para>
<para>The <literal>spring-jdbc</literal> module provides support for
configuring and launching an embedded database which can be used in
integration tests that interact with a database. For details, see <xref
linkend="jdbc-embedded-database-support"/> and <xref
linkend="jdbc-embedded-database-dao-testing"/>.</para>
</section>
<section xml:id="integration-testing-annotations">
<title>Annotations</title>
<section xml:id="integration-testing-annotations-spring">
<title>Spring Testing Annotations</title>
<para>The Spring Framework provides the following set of
<emphasis>Spring-specific</emphasis> annotations that you can use in
your unit and integration tests in conjunction with the TestContext
framework. Refer to the respective Javadoc for further information,
including default attribute values, attribute aliases, and so on.</para>
<itemizedlist>
<listitem>
<para><emphasis role="bold">
<interfacename>@ContextConfiguration</interfacename>
</emphasis></para>
<para>Defines class-level metadata that is used to determine how to
load and configure an
<interfacename>ApplicationContext</interfacename> for integration
tests. Specifically,
<interfacename>@ContextConfiguration</interfacename> declares
<emphasis>either</emphasis> the application context resource
<varname>locations</varname> <emphasis>or</emphasis> the annotated
<varname>classes</varname> that will be used to load the
context.</para>
<para>Resource locations are typically XML configuration files
located in the classpath; whereas, annotated classes are typically
<interfacename>@Configuration</interfacename> classes. However,
resource locations can also refer to files in the file system, and
annotated classes can be component classes, etc.</para>
<programlisting language="java"><emphasis role="bold">@ContextConfiguration</emphasis>("/test-config.xml")
public class XmlApplicationContextTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<programlisting language="java"><emphasis role="bold">@ContextConfiguration</emphasis>(<emphasis
role="bold">classes</emphasis> = TestConfig.class)
public class ConfigClassApplicationContextTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para>As an alternative or in addition to declaring resource
locations or annotated classes,
<interfacename>@ContextConfiguration</interfacename> may be used to
declare <interfacename>ApplicationContextInitializer</interfacename>
classes.</para>
<programlisting language="java"><emphasis role="bold">@ContextConfiguration</emphasis>(<emphasis
role="bold">initializers</emphasis> = CustomContextIntializer.class)
public class ContextInitializerTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para><interfacename>@ContextConfiguration</interfacename> may
optionally be used to declare the
<interfacename>ContextLoader</interfacename> strategy as well. Note,
however, that you typically do not need to explicitly configure the
loader since the default loader supports either resource
<varname>locations</varname> or annotated <varname>classes</varname>
as well as <varname>initializers</varname>.</para>
<programlisting language="java"><emphasis role="bold">@ContextConfiguration</emphasis>(<emphasis
role="bold">locations</emphasis> = "/test-context.xml", <emphasis
role="bold">loader</emphasis> = CustomContextLoader.class)
public class CustomLoaderXmlApplicationContextTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<note>
<para><interfacename>@ContextConfiguration</interfacename>
provides support for <emphasis>inheriting</emphasis> resource
locations or configuration classes as well as context initializers
declared by superclasses by default.</para>
</note>
<para>See <xref linkend="testcontext-ctx-management"/> and the
Javadoc for <interfacename>@ContextConfiguration</interfacename> for
further details.</para>
</listitem>
<listitem>
<para><emphasis
role="bold"><interfacename>@WebAppConfiguration</interfacename></emphasis></para>
<para>A class-level annotation that is used to declare that the
<interfacename>ApplicationContext</interfacename> loaded for an
integration test should be a
<interfacename>WebApplicationContext</interfacename>. The mere
presence of <interfacename>@WebAppConfiguration</interfacename> on a
test class ensures that a
<interfacename>WebApplicationContext</interfacename> will be loaded
for the test, using the default value of
<literal>"file:src/main/webapp"</literal> for the path to the root
of the web application (i.e., the <emphasis>resource base
path</emphasis>). The resource base path is used behind the scenes
to create a <classname>MockServletContext</classname> which serves
as the <interfacename>ServletContext</interfacename> for the test's
<interfacename>WebApplicationContext</interfacename>.</para>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@WebAppConfiguration</emphasis>
public class WebAppTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para>To override the default, specify a different base resource
path via the <emphasis>implicit</emphasis>
<interfacename>value</interfacename> attribute. Both
<literal>classpath:</literal> and <literal>file:</literal> resource
prefixes are supported. If no resource prefix is supplied the path
is assumed to be a file system resource.</para>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@WebAppConfiguration("classpath:test-web-resources")</emphasis>
public class WebAppTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para>Note that <interfacename>@WebAppConfiguration</interfacename>
must be used in conjunction with
<interfacename>@ContextConfiguration</interfacename>, either within
a single test class or within a test class hierarchy. See the
Javadoc for <interfacename>@WebAppConfiguration</interfacename> for
further details.</para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@ContextHierarchy</interfacename></emphasis></para>
<para>A class-level annotation that is used to define a hierarchy of
<interfacename>ApplicationContext</interfacename>s for integration
tests. <interfacename>@ContextHierarchy</interfacename> should be
declared with a list of one or more
<interfacename>@ContextConfiguration</interfacename> instances, each
of which defines a level in the context hierarchy. The following
examples demonstrate the use of
<interfacename>@ContextHierarchy</interfacename> within a single
test class; however,
<interfacename>@ContextHierarchy</interfacename> can also be used
within a test class hierarchy.</para>
<programlisting language="java">@ContextHierarchy({
@ContextConfiguration("/parent-config.xml"),
@ContextConfiguration("/child-config.xml")
})
public class ContextHierarchyTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<programlisting language="java">@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(classes = AppConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
public class WebIntegrationTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para>If you need to merge or override the configuration for a given
level of the context hierarchy within a test class hierarchy, you
must explicitly name that level by supplying the same value to the
<varname>name</varname> attribute in
<interfacename>@ContextConfiguration</interfacename> at each
corresponding level in the class hierarchy. See <xref
linkend="testcontext-ctx-management-ctx-hierarchies"/> and the
Javadoc for <interfacename>@ContextHierarchy</interfacename> for
further examples.</para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@ActiveProfiles</interfacename> </emphasis></para>
<para>A class-level annotation that is used to declare which
<emphasis>bean definition profiles</emphasis> should be active when
loading an <interfacename>ApplicationContext</interfacename> for
test classes.</para>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@ActiveProfiles</emphasis>("dev")
public class DeveloperTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@ActiveProfiles</emphasis>({"dev", "integration"})
public class DeveloperIntegrationTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<note>
<para><interfacename>@ActiveProfiles</interfacename> provides
support for <emphasis>inheriting</emphasis> active bean definition
profiles declared by superclasses by default.</para>
</note>
<para>See <xref linkend="testcontext-ctx-management-env-profiles"/>
and the Javadoc for <interfacename>@ActiveProfiles</interfacename>
for examples and further details.</para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@DirtiesContext</interfacename> </emphasis></para>
<para>Indicates that the underlying Spring
<interfacename>ApplicationContext</interfacename> has been
<emphasis>dirtied</emphasis> during the execution of a test (i.e.,
modified or corrupted in some manner — for example, by changing the
state of a singleton bean) and should be closed, regardless of
whether the test passed. When an application context is marked
<emphasis>dirty</emphasis>, it is removed from the testing
framework's cache and closed. As a consequence, the underlying
Spring container will be rebuilt for any subsequent test that
requires a context with the same configuration metadata.</para>
<para><interfacename>@DirtiesContext</interfacename> can be used as
both a class-level and method-level annotation within the same test
class. In such scenarios, the
<interfacename>ApplicationContext</interfacename> is marked as
<emphasis>dirty</emphasis> after any such annotated method as well
as after the entire class. If the <classname>ClassMode</classname>
is set to <literal>AFTER_EACH_TEST_METHOD</literal>, the context is
marked dirty after each test method in the class.</para>
<para>The following examples explain when the context would be
dirtied for various configuration scenarios:</para>
<itemizedlist>
<listitem>
<para>After the current test class, when declared on a class
with class mode set to <literal>AFTER_CLASS</literal> (i.e., the
default class mode).</para>
<programlisting language="java"><emphasis role="bold">@DirtiesContext</emphasis>
public class ContextDirtyingTests {
<lineannotation>// some tests that result in the Spring container being dirtied</lineannotation>
}</programlisting>
</listitem>
<listitem>
<para>After each test method in the current test class, when
declared on a class with class mode set to
<literal>AFTER_EACH_TEST_METHOD.</literal><programlisting
language="java"><emphasis role="bold">@DirtiesContext</emphasis>(<emphasis
role="bold">classMode</emphasis> = ClassMode.AFTER_EACH_TEST_METHOD)
public class ContextDirtyingTests {
<lineannotation>// some tests that result in the Spring container being dirtied</lineannotation>
}</programlisting></para>
</listitem>
<listitem>
<para>After the current test, when declared on a method.</para>
<programlisting language="java"><emphasis role="bold">@DirtiesContext</emphasis>
@Test
public void testProcessWhichDirtiesAppCtx() {
<lineannotation>// some logic that results in the Spring container being dirtied</lineannotation>
}</programlisting>
</listitem>
</itemizedlist>
<para>If <interfacename>@DirtiesContext</interfacename> is used in a
test whose context is configured as part of a context hierarchy via
<interfacename>@ContextHierarchy</interfacename>, the
<varname>hierarchyMode</varname> flag can be used to control how the
context cache is cleared. By default an
<emphasis>exhaustive</emphasis> algorithm will be used that clears
the context cache including not only the current level but also all
other context hierarchies that share an ancestor context common to
the current test; all
<interfacename>ApplicationContext</interfacename>s that reside in a
sub-hierarchy of the common ancestor context will be removed from
the context cache and closed. If the <emphasis>exhaustive</emphasis>
algorithm is overkill for a particular use case, the simpler
<emphasis>current level</emphasis> algorithm can be specified
instead, as seen below.</para>
<programlisting language="java">@ContextHierarchy({
@ContextConfiguration("/parent-config.xml"),
@ContextConfiguration("/child-config.xml")
})
public class BaseTests {
<lineannotation>// class body...</lineannotation>
}
public class ExtendedTests extends BaseTests {
@Test
@DirtiesContext(<emphasis role="bold">hierarchyMode = HierarchyMode.CURRENT_LEVEL</emphasis>)
public void test() {
<lineannotation>// some logic that results in the child context being dirtied</lineannotation>
}
}</programlisting>
<para>For further details regarding the
<constant>EXHAUSTIVE</constant> and
<constant>CURRENT_LEVEL</constant> algorithms see the Javadoc for
<interfacename>DirtiesContext.HierarchyMode</interfacename>.</para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@TestExecutionListeners</interfacename>
</emphasis></para>
<para>Defines class-level metadata for configuring which
<interfacename>TestExecutionListener</interfacename>s should be
registered with the <classname>TestContextManager</classname>.
Typically, <interfacename>@TestExecutionListeners</interfacename> is
used in conjunction with
<interfacename>@ContextConfiguration</interfacename>.</para>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@TestExecutionListeners</emphasis>({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
public class CustomTestExecutionListenerTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<para><interfacename>@TestExecutionListeners</interfacename>
supports <emphasis>inherited</emphasis> listeners by default. See
the Javadoc for an example and further details.</para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@TransactionConfiguration</interfacename>
</emphasis></para>
<para>Defines class-level metadata for configuring transactional
tests. Specifically, the bean name of the
<interfacename>PlatformTransactionManager</interfacename> that
should be used to drive transactions can be explicitly specified if
there are multiple beans of type
<interfacename>PlatformTransactionManager</interfacename> in the
test's <interfacename>ApplicationContext</interfacename> and if the
bean name of the desired
<interfacename>PlatformTransactionManager</interfacename> is not
"transactionManager". In addition, you can change the
<literal>defaultRollback</literal> flag to <literal>false</literal>.
Typically, <interfacename>@TransactionConfiguration</interfacename>
is used in conjunction with
<interfacename>@ContextConfiguration</interfacename>.</para>
<programlisting language="java">@ContextConfiguration
<emphasis role="bold">@TransactionConfiguration</emphasis>(<emphasis role="bold">transactionManager</emphasis> = "txMgr", <emphasis
role="bold">defaultRollback</emphasis> = false)
public class CustomConfiguredTransactionalTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
<note>
<para>If the default conventions are sufficient for your test
configuration, you can avoid using
<interfacename>@TransactionConfiguration</interfacename>
altogether. In other words, if you have only one transaction
manger — or if you have multiple transaction mangers but the
transaction manager for tests is named "transactionManager" or
specified via a
<interfacename>TransactionManagementConfigurer</interfacename> —
and if you want transactions to roll back automatically, then
there is no need to annotate your test class with
<interfacename>@TransactionConfiguration</interfacename>.</para>
</note>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@Rollback</interfacename> </emphasis></para>
<para>Indicates whether the transaction for the annotated test
method should be <emphasis>rolled back</emphasis> after the test
method has completed. If <literal>true</literal>, the transaction is
rolled back; otherwise, the transaction is committed. Use
<interfacename>@Rollback</interfacename> to override the default
rollback flag configured at the class level.</para>
<programlisting language="java"><emphasis role="bold">@Rollback</emphasis>(false)
@Test
public void testProcessWithoutRollback() {
<lineannotation>// ...</lineannotation>
}</programlisting>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@BeforeTransaction</interfacename> </emphasis></para>
<para>Indicates that the annotated <literal>public void</literal>
method should be executed <emphasis>before</emphasis> a transaction
is started for test methods configured to run within a transaction
via the <interfacename>@Transactional</interfacename>
annotation.</para>
<programlisting language="java"><emphasis role="bold">@BeforeTransaction
</emphasis>public void beforeTransaction() {
<lineannotation>// logic to be executed before a transaction is started</lineannotation>
}</programlisting>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@AfterTransaction</interfacename> </emphasis></para>
<para>Indicates that the annotated <literal>public void</literal>
method should be executed <emphasis>after</emphasis> a transaction
has ended for test methods configured to run within a transaction
via the <interfacename>@Transactional</interfacename>
annotation.</para>
<programlisting language="java"><emphasis role="bold">@AfterTransaction
</emphasis>public void afterTransaction() {
<lineannotation>// logic to be executed after a transaction has ended</lineannotation>
}</programlisting>
</listitem>
</itemizedlist>
</section>
<section xml:id="integration-testing-annotations-standard">
<title>Standard Annotation Support</title>
<para>The following annotations are supported with standard semantics
for all configurations of the Spring TestContext Framework. Note that
these annotations are not specific to tests and can be used anywhere in
the Spring Framework.</para>
<itemizedlist>
<listitem>
<para><emphasis role="bold">
<interfacename>@Autowired</interfacename> </emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@Qualifier</interfacename> </emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@Resource</interfacename> </emphasis>
(javax.annotation) <emphasis>if JSR-250 is present</emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold"> <interfacename>@Inject</interfacename>
</emphasis> (javax.inject) <emphasis>if JSR-330 is
present</emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold"> <interfacename>@Named</interfacename>
</emphasis> (javax.inject) <emphasis>if JSR-330 is
present</emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@PersistenceContext</interfacename> </emphasis>
(javax.persistence) <emphasis>if JPA is present</emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@PersistenceUnit</interfacename> </emphasis>
(javax.persistence) <emphasis>if JPA is present</emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@Required</interfacename> </emphasis></para>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@Transactional</interfacename> </emphasis></para>
</listitem>
</itemizedlist>
<note>
<title>JSR-250 Lifecycle Annotations</title>
<para>In the Spring TestContext Framework
<interfacename>@PostConstruct</interfacename> and
<interfacename>@PreDestroy</interfacename> may be used with standard
semantics on any application components configured in the
<interfacename>ApplicationContext</interfacename>; however, these
lifecycle annotations have limited usage within an actual test
class.</para>
<para>If a method within a test class is annotated with
<interfacename>@PostConstruct</interfacename>, that method will be
executed before any <emphasis>before</emphasis> methods of the
underlying test framework (e.g., methods annotated with JUnit's
<interfacename>@Before</interfacename>), and that will apply for every
test method in the test class. On the other hand, if a method within a
test class is annotated with
<interfacename>@PreDestroy</interfacename>, that method will <emphasis
role="bold">never</emphasis> be executed. Within a test class it is
therefore recommended to use test lifecycle callbacks from the
underlying test framework instead of
<interfacename>@PostConstruct</interfacename> and
<interfacename>@PreDestroy</interfacename>.</para>
</note>
</section>
<section xml:id="integration-testing-annotations-junit">
<title>Spring JUnit Testing Annotations</title>
<para>The following annotations are <emphasis>only</emphasis> supported
when used in conjunction with the <link
linkend="testcontext-junit4-runner">SpringJUnit4ClassRunner</link> or
the <link linkend="testcontext-support-classes-junit4">JUnit</link>
support classes.</para>
<itemizedlist>
<listitem>
<para><emphasis role="bold">
<interfacename>@IfProfileValue</interfacename> </emphasis></para>
<para>Indicates that the annotated test is enabled for a specific
testing environment. If the configured
<classname>ProfileValueSource</classname> returns a matching
<literal>value</literal> for the provided <literal>name</literal>,
the test is enabled. This annotation can be applied to an entire
class or to individual methods. Class-level usage overrides
method-level usage.</para>
<programlisting language="java"><emphasis role="bold">@IfProfileValue</emphasis>(<emphasis
role="bold">name</emphasis>="java.vendor", <emphasis role="bold">value</emphasis>="Sun Microsystems Inc.")
@Test
public void testProcessWhichRunsOnlyOnSunJvm() {
<lineannotation>// some logic that should run only on Java VMs from Sun Microsystems</lineannotation>
}</programlisting>
<para>Alternatively, you can configure
<interfacename>@IfProfileValue</interfacename> with a list of
<literal>values</literal> (with <emphasis>OR</emphasis> semantics)
to achieve TestNG-like support for <emphasis>test groups</emphasis>
in a JUnit environment. Consider the following example:</para>
<programlisting language="java"><emphasis role="bold">@IfProfileValue</emphasis>(<emphasis
role="bold">name</emphasis>="test-groups", <emphasis role="bold">values</emphasis>={"unit-tests", "integration-tests"})
@Test
public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
<lineannotation>// some logic that should run only for unit and integration test groups</lineannotation>
}</programlisting>
</listitem>
<listitem>
<para><emphasis role="bold">
<interfacename>@ProfileValueSourceConfiguration</interfacename>
</emphasis></para>
<para>Class-level annotation that specifies what type of
<literal>ProfileValueSource</literal> to use when retrieving
<emphasis>profile values</emphasis> configured through the
<interfacename>@IfProfileValue</interfacename> annotation. If
<interfacename>@ProfileValueSourceConfiguration</interfacename> is
not declared for a test,
<classname>SystemProfileValueSource</classname> is used by
default.</para>
<programlisting language="java"><emphasis role="bold">@ProfileValueSourceConfiguration</emphasis>(CustomProfileValueSource.class)
public class CustomProfileValueSourceTests {
<lineannotation>// class body...</lineannotation>
}</programlisting>
</listitem>
<listitem>
<para><emphasis role="bold"> <interfacename>@Timed</interfacename>
</emphasis></para>
<para>Indicates that the annotated test method must finish execution
in a specified time period (in milliseconds). If the text execution
time exceeds the specified time period, the test fails.</para>
<para>The time period includes execution of the test method itself,
any repetitions of the test (see
<interfacename>@Repeat</interfacename>), as well as any
<emphasis>set up</emphasis> or <emphasis>tear down</emphasis> of the
test fixture.</para>
<programlisting language="java"><emphasis role="bold">@Timed</emphasis>(millis=1000)
public void testProcessWithOneSecondTimeout() {
<lineannotation>// some logic that should not take longer than 1 second to execute</lineannotation>