4.3.9.RELEASE Spring Framework
334
LoginAction is instantiated using
SpEL expressions that retrieve the username and password from
the current HTTP request. In our test, we will want to configure these request parameters via the mock managed by the TestContext framework.
Request-scoped bean configuration.
beans bean
id =
userService class
= com.example.SimpleUserService
c:loginAction-ref =
loginAction bean
id =
loginAction class
= com.example.LoginAction
c:username =
{request.getParameteruser} c:password={request.getParameterpswd}
scope=request
aop:scoped-proxy bean
beans
In RequestScopedBeanTests
we inject both the UserService
i.e., the subject under test and the MockHttpServletRequest
into our test instance. Within our requestScope
test method we set up our test fixture by setting request parameters in the provided
MockHttpServletRequest . When
the loginUser
method is invoked on our userService
we are assured that the user service has access to the request-scoped
loginAction for the current
MockHttpServletRequest i.e., the one
we just set parameters in. We can then perform assertions against the results based on the known inputs for the username and password.
Request-scoped bean test.
RunWithSpringRunner.class ContextConfiguration
WebAppConfiguration
public class
RequestScopedBeanTests { Autowired
UserService userService; Autowired
MockHttpServletRequest request; Test
public void
requestScope { request.setParameter
user ,
enigma ;
request.setParameter pswd
, prng
; LoginResults results = userService.loginUser;
assert results }
}
The following code snippet is similar to the one we saw above for a request-scoped bean; however, this time the
userService bean has a dependency on a session-scoped
userPreferences bean. Note
that the UserPreferences
bean is instantiated using a SpEL expression that retrieves the theme from the current HTTP session. In our test, we will need to configure a theme in the mock session managed
by the TestContext framework.
Session-scoped bean configuration.
4.3.9.RELEASE Spring Framework
335
beans bean
id =
userService class
= com.example.SimpleUserService
c:userPreferences-ref =
userPreferences bean
id =
userPreferences class
= com.example.UserPreferences
c:theme =
{session.getAttributetheme} scope
= session
aop:scoped-proxy bean
beans
In SessionScopedBeanTests
we inject the UserService
and the MockHttpSession
into our test instance. Within our
sessionScope test method we set up our test fixture by setting the expected
theme attribute in the provided MockHttpSession
. When the processUserPreferences
method is invoked on our userService
we are assured that the user service has access to the session- scoped
userPreferences for the current
MockHttpSession , and we can perform assertions against
the results based on the configured theme.
Session-scoped bean test.
RunWithSpringRunner.class ContextConfiguration
WebAppConfiguration
public class
SessionScopedBeanTests { Autowired
UserService userService; Autowired
MockHttpSession session; Test
public void
sessionScope throws
Exception { session.setAttribute
theme ,
blue ;
Results results = userService.processUserPreferences; assert results
} }
Transaction management
In the
TestContext framework,
transactions are
managed by
the TransactionalTestExecutionListener
which is configured by default, even if you do not explicitly declare
TestExecutionListeners on your test class. To enable support for transactions,
however, you must configure a PlatformTransactionManager
bean in the ApplicationContext
that is loaded via ContextConfiguration
semantics further details are provided below. In addition, you must declare Spring’s
Transactional annotation either at the class or method level
for your tests.
Test-managed transactions
Test-managed transactions
are transactions
that are
managed declaratively
via the
TransactionalTestExecutionListener or programmatically via
TestTransaction see
below. Such transactions should not be confused with Spring-managed transactions i.e., those managed directly by Spring within the
ApplicationContext loaded for tests or application-
managed transactions i.e., those managed programmatically within application code that is invoked via tests. Spring-managed and application-managed transactions will typically participate in test-managed
4.3.9.RELEASE Spring Framework
336
transactions; however, caution should be taken if Spring-managed or application-managed transactions are configured with any propagation type other than
REQUIRED or
SUPPORTS see the discussion on
transaction propagation for details.
Enabling and disabling transactions
Annotating a test method with Transactional
causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated
with Transactional
, each test method within that class hierarchy will be run within a transaction. Test methods that are not annotated with
Transactional at the class or method level will not be
run within a transaction. Furthermore, tests that are annotated with Transactional
but have the propagation
type set to NOT_SUPPORTED
will not be run within a transaction. Note
that AbstractTransactionalJUnit4SpringContextTests
and AbstractTransactionalTestNGSpringContextTests
are preconfigured for transactional support at the class level.
The following example demonstrates a common scenario for writing an integration test for a Hibernate-based
UserRepository . As explained in the section called “Transaction rollback and
commit behavior”, there is no need to clean up the database after the createUser
method is executed since any changes made to the database will be automatically rolled back by the
TransactionalTestExecutionListener . See Section 15.7, “PetClinic Example” for an additional
example.
RunWithSpringRunner.class ContextConfigurationclasses = TestConfig.class
Transactional
public class
HibernateUserRepositoryTests { Autowired
HibernateUserRepository repository; Autowired
SessionFactory sessionFactory; JdbcTemplate jdbcTemplate;
Autowired
public void
setDataSourceDataSource dataSource {
this .jdbcTemplate =
new JdbcTemplatedataSource;
} Test
public void
createUser { track initial state in test database:
final int
count = countRowsInTable user
; User user =
new User...;
repository.saveuser; Manual flush is required to avoid false positive in test
sessionFactory.getCurrentSession.flush; assertNumUserscount + 1;
}
protected int
countRowsInTableString tableName {
return JdbcTestUtils.countRowsInTable
this .jdbcTemplate, tableName;
}
protected void
assertNumUsers int
expected { assertEquals
Number of rows in the [user] table. , expected, countRowsInTable
user ;
} }
4.3.9.RELEASE Spring Framework
337
Transaction rollback and commit behavior
By default, test transactions will be automatically rolled back after completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the
Commit and
Rollback annotations. See the corresponding entries in the
annotation support section for further
details.
Programmatic transaction management
Since Spring Framework 4.1, it is possible to interact with test-managed transactions programmatically via the static methods in
TestTransaction . For example,
TestTransaction may be used within test methods, before methods, and after methods to start or end
the current test-managed transaction or to configure the current test-managed transaction for rollback or commit. Support for
TestTransaction is automatically available whenever the
TransactionalTestExecutionListener is enabled.
The following example demonstrates some of the features of TestTransaction
. Consult the javadocs for
TestTransaction for further details.
ContextConfigurationclasses = TestConfig.class
public class
ProgrammaticTransactionManagementTests extends
AbstractTransactionalJUnit4SpringContextTests { Test
public void
transactionalTest { assert initial state in test database:
assertNumUsers2; deleteFromTables
user ;
changes to the database will be committed TestTransaction.flagForCommit;
TestTransaction.end; assertFalseTestTransaction.isActive;
assertNumUsers0; TestTransaction.start;
perform other actions against the database that will be automatically rolled back after the test completes...
}
protected void
assertNumUsers int
expected { assertEquals
Number of rows in the [user] table. , expected, countRowsInTable
user ;
} }
Executing code outside of a transaction
Occasionally you need to execute certain code before or after a transactional test method but outside the transactional context — for example, to verify the initial database state prior to execution of your test or to
verify expected transactional commit behavior after test execution if the test was configured to commit the transaction.
TransactionalTestExecutionListener supports the
BeforeTransaction and
AfterTransaction annotations exactly for such scenarios. Simply annotate any
void method
in a test class or any void
default method in a test interface with one of these annotations, and the
TransactionalTestExecutionListener ensures that your before transaction method or after
transaction method is executed at the appropriate time.
4.3.9.RELEASE Spring Framework
338
Tip
Any before methods such as methods annotated with JUnit 4’s Before
and any after methods such as methods annotated with JUnit 4’s
After are executed within a transaction. In addition,
methods annotated with BeforeTransaction
or AfterTransaction
are naturally not executed for test methods that are not configured to run within a transaction.
Configuring a transaction manager
TransactionalTestExecutionListener expects
a PlatformTransactionManager
bean to
be defined
in the
Spring ApplicationContext
for the
test. In
case there
are multiple
instances of
PlatformTransactionManager within
the test’s
ApplicationContext ,
a qualifier
may be
declared via
TransactionalmyTxMgr or
TransactionaltransactionManager = myTxMgr , or
TransactionManagementConfigurer can be implemented by an
Configuration class. Consult
the javadocs for TestContextTransactionUtils.retrieveTransactionManager
for details on the algorithm used to look up a transaction manager in the test’s
ApplicationContext .
Demonstration of all transaction-related annotations
The following JUnit 4 based example displays a fictitious integration testing scenario highlighting all
transaction-related annotations. The example is not intended to demonstrate best practices but rather
to demonstrate how these annotations can be used. Consult the annotation support
section for further information and configuration examples.
Transaction management for Sql
contains an additional example using
Sql for declarative SQL script execution with default transaction rollback semantics.
RunWithSpringRunner.class ContextConfiguration
TransactionaltransactionManager = txMgr Commit
public class
FictitiousTransactionalTest {
BeforeTransaction void
verifyInitialDatabaseState { logic to verify the initial state before a transaction is started
} Before
public void
setUpTestDataWithinTransaction { set up test data within the transaction
} Test
overrides the class-level Commit setting
Rollback public
void modifyDatabaseWithinTransaction {
logic which uses the test data and modifies database state }
After
public void
tearDownWithinTransaction { execute tear down logic within the transaction
}
AfterTransaction void
verifyFinalDatabaseState { logic to verify the final state after transaction has rolled back
} }
4.3.9.RELEASE Spring Framework
339
Avoid false positives when testing ORM code
When you test application code that manipulates the state of a Hibernate session or JPA persistence context, make sure to flush the underlying unit of work within test methods that
execute that code. Failing to flush the underlying unit of work can produce false positives: your test may pass, but the same code throws an exception in a live, production environment. In the
following Hibernate-based example test case, one method demonstrates a false positive, and the other method correctly exposes the results of flushing the session. Note that this applies to any
ORM frameworks that maintain an in-memory unit of work.
... Autowired
SessionFactory sessionFactory; Transactional
Test no expected exception
public void
falsePositive { updateEntityInHibernateSession;
False positive: an exception will be thrown once the Hibernate Session is finally flushed i.e., in production code
} Transactional
Testexpected = ...
public void
updateWithSessionFlush { updateEntityInHibernateSession;
Manual flush is required to avoid false positive in test sessionFactory.getCurrentSession.flush;
} ...
Or for JPA:
... PersistenceContext
EntityManager entityManager; Transactional
Test no expected exception
public void
falsePositive { updateEntityInJpaPersistenceContext;
False positive: an exception will be thrown once the JPA EntityManager is finally flushed i.e., in production code
} Transactional
Testexpected = ...
public void
updateWithEntityManagerFlush { updateEntityInJpaPersistenceContext;
Manual flush is required to avoid false positive in test entityManager.flush;
} ...
Executing SQL scripts
When writing integration tests against a relational database, it is often beneficial to execute SQL scripts to modify the database schema or insert test data into tables. The
spring-jdbc module provides
support for initializing an embedded or existing database by executing SQL scripts when the Spring
4.3.9.RELEASE Spring Framework
340
ApplicationContext is loaded. See Section 19.8, “Embedded database support” and the section
called “Testing data access logic with an embedded database” for details. Although it is very useful to initialize a database for testing once when the
ApplicationContext is
loaded, sometimes it is essential to be able to modify the database during integration tests. The following sections explain how to execute SQL scripts programmatically and declaratively during integration tests.
Executing SQL scripts programmatically
Spring provides the following options for executing SQL scripts programmatically within integration test methods.
• org.springframework.jdbc.datasource.init.ScriptUtils
• org.springframework.jdbc.datasource.init.ResourceDatabasePopulator
• org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests
• org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests
ScriptUtils provides a collection of static utility methods for working with SQL scripts and is mainly
intended for internal use within the framework. However, if you require full control over how SQL scripts are parsed and executed,
ScriptUtils may suit your needs better than some of the other alternatives
described below. Consult the javadocs for individual methods in ScriptUtils
for further details. ResourceDatabasePopulator
provides a simple object-based API for programmatically populating, initializing, or cleaning up a database using SQL scripts defined in external resources.
ResourceDatabasePopulator provides options for configuring the character encoding, statement
separator, comment delimiters, and error handling flags used when parsing and executing the scripts, and each of the configuration options has a reasonable default value. Consult the javadocs for
details on default values. To execute the scripts configured in a ResourceDatabasePopulator
, you can invoke either the
populateConnection method to execute the populator against a
java.sql.Connection or the
executeDataSource method to execute the populator against a
javax.sql.DataSource . The following example specifies SQL scripts for a test schema and test
data, sets the statement separator to , and then executes the scripts against a
DataSource .
Test
public void
databaseTest { ResourceDatabasePopulator populator =
new ResourceDatabasePopulator;
populator.addScripts
new ClassPathResource
test-schema.sql ,
new ClassPathResource
test-data.sql ;
populator.setSeparator ;
populator.execute this
.dataSource; execute code that uses the test schema and data
}
Note that
ResourceDatabasePopulator internally
delegates to
ScriptUtils for
parsing and executing SQL scripts. Similarly, the executeSqlScript..
methods in AbstractTransactionalJUnit4SpringContextTests
and AbstractTransactionalTestNGSpringContextTests
internally use
a ResourceDatabasePopulator
for executing SQL scripts. Consult the javadocs for the various executeSqlScript..
methods for further details.
Executing SQL scripts declaratively with Sql
In addition to the aforementioned mechanisms for executing SQL scripts programmatically, SQL scripts can also be configured declaratively in the Spring TestContext Framework. Specifically, the
Sql
4.3.9.RELEASE Spring Framework
341
annotation can be declared on a test class or test method to configure the resource paths to SQL scripts that should be executed against a given database either before or after an integration test method. Note
that method-level declarations override class-level declarations and that support for Sql
is provided by the
SqlScriptsTestExecutionListener which is enabled by default.
Path resource semantics
Each path will be interpreted as a Spring Resource
. A plain path — for example, schema.sql
— will be treated as a classpath resource that is relative to the package in which the test class is defined.
A path starting with a slash will be treated as an absolute classpath resource, for example: org
exampleschema.sql . A path which references a URL e.g., a path prefixed with
classpath: ,
file: ,
http: , etc. will be loaded using the specified resource protocol.
The following example demonstrates how to use Sql
at the class level and at the method level within a JUnit 4 based integration test class.
RunWithSpringRunner.class ContextConfiguration
Sqltest-schema.sql
public class
DatabaseTests { Test
public void
emptySchemaTest { execute code that uses the test schema without any test data
} Test
Sql{test-schema.sql, test-user-data.sql}
public void
userTest { execute code that uses the test schema and test data
} }
Default script detection
If no SQL scripts are specified, an attempt will be made to detect a default
script depending on where Sql
is declared. If a default cannot be detected, an IllegalStateException
will be thrown. • class-level declaration: if the annotated test class is
com.example.MyTest , the corresponding
default script is classpath:comexampleMyTest.sql
. • method-level declaration: if the annotated test method is named
testMethod and is defined in
the class com.example.MyTest
, the corresponding default script is classpath:comexample
MyTest.testMethod.sql .
Declaring multiple Sql
sets
If multiple sets of SQL scripts need to be configured for a given test class or test method but with different syntax configuration, different error handling rules, or different execution phases per set, it
is possible to declare multiple instances of Sql
. With Java 8, Sql
can be used as a repeatable annotation. Otherwise, the
SqlGroup annotation can be used as an explicit container for declaring
multiple instances of Sql
. The following example demonstrates the use of
Sql as a repeatable annotation using Java 8. In this
scenario the test-schema.sql
script uses a different syntax for single-line comments.
4.3.9.RELEASE Spring Framework
342
Test Sqlscripts = test-schema.sql, config = SqlConfigcommentPrefix = `
Sqltest-user-data.sql
public void
userTest { execute code that uses the test schema and test data
}
The following example is identical to the above except that the Sql
declarations are grouped together within
SqlGroup for compatibility with Java 6 and Java 7.
Test SqlGroup{
Sqlscripts = test-schema.sql, config = SqlConfigcommentPrefix = `, Sqltest-user-data.sql
}
public void
userTest { execute code that uses the test schema and test data
}
Script execution phases
By default, SQL scripts will be executed before the corresponding test method. However, if a particular set of scripts needs to be executed after the test method — for example, to clean up database
state — the executionPhase
attribute in Sql
can be used as seen in the following example. Note that
ISOLATED and
AFTER_TEST_METHOD are statically imported from
Sql.TransactionMode and
Sql.ExecutionPhase respectively.
Test Sql
scripts = create-test-data.sql, config = SqlConfigtransactionMode = ISOLATED
Sql scripts = delete-test-data.sql,
config = SqlConfigtransactionMode = ISOLATED, executionPhase = AFTER_TEST_METHOD
public void
userTest { execute code that needs the test data to be committed
to the database outside of the tests transaction }
Script configuration with SqlConfig
Configuration for script parsing and error handling can be configured via the SqlConfig
annotation. When declared as a class-level annotation on an integration test class,
SqlConfig serves as global
configuration for all SQL scripts within the test class hierarchy. When declared directly via the config
attribute of the Sql
annotation, SqlConfig
serves as local configuration for the SQL scripts declared within the enclosing
Sql annotation. Every attribute in
SqlConfig has an implicit default value which
is documented in the javadocs of the corresponding attribute. Due to the rules defined for annotation attributes in the Java Language Specification, it is unfortunately not possible to assign a value of
null to an annotation attribute. Thus, in order to support overrides of inherited global configuration,
SqlConfig attributes have an explicit default value of either
for Strings or DEFAULT
for Enums. This approach allows local declarations of
SqlConfig to selectively override individual attributes
from global declarations of SqlConfig
by providing a value other than or
DEFAULT . Global
SqlConfig attributes are inherited whenever local
SqlConfig attributes do not supply an explicit
value other than or
DEFAULT . Explicit local configuration therefore overrides global configuration.
The configuration options provided by Sql
and SqlConfig
are equivalent to those supported by
ScriptUtils and
ResourceDatabasePopulator but are a superset of those provided by
4.3.9.RELEASE Spring Framework
343
the jdbc:initialize-database
XML namespace element. Consult the javadocs of individual attributes in
Sql and
SqlConfig for details.
Transaction management for Sql
By default, the SqlScriptsTestExecutionListener
will infer the desired transaction semantics for scripts configured via
Sql . Specifically, SQL scripts will be executed without a transaction,
within an existing Spring-managed transaction — for example, a transaction managed by the TransactionalTestExecutionListener
for a test annotated with Transactional
— or within an isolated transaction, depending on the configured value of the
transactionMode attribute in
SqlConfig and the presence of a
PlatformTransactionManager in the test’s
ApplicationContext . As a bare minimum however, a
javax.sql.DataSource must be present
in the test’s ApplicationContext
. If the algorithms used by
SqlScriptsTestExecutionListener to detect a
DataSource and
PlatformTransactionManager and infer the transaction semantics do not suit your needs,
you may specify explicit names via the dataSource
and transactionManager
attributes of
SqlConfig . Furthermore, the transaction propagation behavior can be controlled via the
transactionMode attribute of
SqlConfig — for example, if scripts should be executed in
an isolated transaction. Although a thorough discussion of all supported options for transaction management with
Sql is beyond the scope of this reference manual, the javadocs for
SqlConfig and
SqlScriptsTestExecutionListener provide detailed information, and the following example
demonstrates a typical testing scenario using JUnit 4 and transactional tests with Sql
. Note that there is no need to clean up the database after the
usersTest method is executed since any
changes made to the database either within the test method or within the test-data.sql
script will be automatically rolled back by the
TransactionalTestExecutionListener see
transaction management
for details.
RunWithSpringRunner.class ContextConfigurationclasses = TestDatabaseConfig.class
Transactional
public class
TransactionalSqlScriptsTests {
protected JdbcTemplate jdbcTemplate;
Autowired
public void
setDataSourceDataSource dataSource {
this .jdbcTemplate =
new JdbcTemplatedataSource;
} Test
Sqltest-data.sql
public void
usersTest { verify state in test database:
assertNumUsers2; execute code that uses the test data...
}
protected int
countRowsInTableString tableName {
return JdbcTestUtils.countRowsInTable
this .jdbcTemplate, tableName;
}
protected void
assertNumUsers int
expected { assertEquals
Number of rows in the [user] table. , expected, countRowsInTable
user ;
} }
4.3.9.RELEASE Spring Framework
344
TestContext Framework support classes
Spring JUnit 4 Runner
The Spring
TestContext Framework
offers full
integration with
JUnit 4
through a
custom runner
supported on
JUnit 4.12
or higher.
By annotating
test classes
with RunWithSpringJUnit4ClassRunner.class
or the
shorter RunWithSpringRunner.class
variant, developers can implement standard JUnit 4 based unit and integration tests and simultaneously reap the benefits of the TestContext framework such as support
for loading application contexts, dependency injection of test instances, transactional test method execution, and so on. If you would like to use the Spring TestContext Framework with an alternative
runner such as JUnit 4’s Parameterized
or third-party runners such as the MockitoJUnitRunner
, you may optionally use
Spring’s support for JUnit rules instead.
The following code listing displays the minimal requirements for configuring a test class to run with the custom Spring
Runner .
TestExecutionListeners is configured with an empty list in order to
disable the default listeners, which otherwise would require an ApplicationContext
to be configured through
ContextConfiguration .
RunWithSpringRunner.class TestExecutionListeners{}
public class
SimpleTest { Test
public void
testMethod { execute test logic...
} }
Spring JUnit 4 Rules
The org.springframework.test.context.junit4.rules
package provides the following JUnit 4 rules supported on JUnit 4.12 or higher.
• SpringClassRule
• SpringMethodRule
SpringClassRule is a JUnit
TestRule that supports class-level features of the Spring TestContext
Framework; whereas, SpringMethodRule
is a JUnit MethodRule
that supports instance-level and method-level features of the Spring TestContext Framework.
In contrast to the SpringRunner
, Spring’s rule-based JUnit support has the advantage that it is independent of any
org.junit.runner.Runner implementation and can therefore be combined
with existing alternative runners like JUnit 4’s Parameterized
or third-party runners such as the MockitoJUnitRunner
. In order to support the full functionality of the TestContext framework, a
SpringClassRule must be
combined with a SpringMethodRule
. The following example demonstrates the proper way to declare these rules in an integration test.
4.3.9.RELEASE Spring Framework
345
Optionally specify a non-Spring Runner via RunWith... ContextConfiguration
public class
IntegrationTest { ClassRule
public static
final SpringClassRule SPRING_CLASS_RULE =
new SpringClassRule;
Rule
public final
SpringMethodRule springMethodRule = new
SpringMethodRule; Test
public void
testMethod { execute test logic...
} }
JUnit 4 support classes
The org.springframework.test.context.junit4
package provides the following support classes for JUnit 4 based test cases supported on JUnit 4.12 or higher.
• AbstractJUnit4SpringContextTests
• AbstractTransactionalJUnit4SpringContextTests
AbstractJUnit4SpringContextTests is an abstract base test class that integrates the Spring
TestContext Framework with explicit ApplicationContext
testing support in a JUnit 4 environment. When you extend
AbstractJUnit4SpringContextTests , you can access a
protected applicationContext
instance variable that can be used to perform explicit bean lookups or to test the state of the context as a whole.
AbstractTransactionalJUnit4SpringContextTests is an abstract transactional extension
of AbstractJUnit4SpringContextTests
that adds
some convenience
functionality for
JDBC access.
This class
expects a
javax.sql.DataSource bean
and a
PlatformTransactionManager bean to be defined in the
ApplicationContext . When you
extend AbstractTransactionalJUnit4SpringContextTests
you can access a protected
jdbcTemplate instance variable that can be used to execute SQL statements to query
the database. Such queries can be used to confirm database state both prior to and after 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
false positives . As mentioned in Section 15.3,
“JDBC Testing Support”, AbstractTransactionalJUnit4SpringContextTests
also provides convenience methods which delegate to methods in
JdbcTestUtils using the aforementioned
jdbcTemplate . Furthermore,
AbstractTransactionalJUnit4SpringContextTests provides
an executeSqlScript..
method for executing SQL scripts against the configured DataSource
.
Tip
These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy, you can configure your own custom test classes by using
RunWithSpringRunner.class or
Spring’s JUnit rules .
TestNG support classes
The org.springframework.test.context.testng
package provides the following support classes for TestNG based test cases.
4.3.9.RELEASE Spring Framework
346
• AbstractTestNGSpringContextTests
• AbstractTransactionalTestNGSpringContextTests
AbstractTestNGSpringContextTests is an abstract base test class that integrates the Spring
TestContext Framework with explicit ApplicationContext
testing support in a TestNG environment. When you extend
AbstractTestNGSpringContextTests , you can access a
protected applicationContext
instance variable that can be used to perform explicit bean lookups or to test the state of the context as a whole.
AbstractTransactionalTestNGSpringContextTests is an abstract transactional extension
of AbstractTestNGSpringContextTests
that adds
some convenience
functionality for
JDBC access.
This class
expects a
javax.sql.DataSource bean
and a
PlatformTransactionManager bean to be defined in the
ApplicationContext . When you
extend AbstractTransactionalTestNGSpringContextTests
you can access a protected
jdbcTemplate instance variable that can be used to execute SQL statements to query
the database. Such queries can be used to confirm database state both prior to and after 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
false positives . As mentioned in Section 15.3,
“JDBC Testing Support”, AbstractTransactionalTestNGSpringContextTests
also provides convenience methods which delegate to methods in
JdbcTestUtils using the aforementioned
jdbcTemplate . Furthermore,
AbstractTransactionalTestNGSpringContextTests provides
an executeSqlScript..
method for executing SQL scripts against the configured DataSource
.
Tip
These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy, you can configure your own custom test classes
by using ContextConfiguration
, TestExecutionListeners
, and so on, and by manually instrumenting your test class with a
TestContextManager . See the source code of
AbstractTestNGSpringContextTests for an example of how to instrument your test class.
15.6 Spring MVC Test Framework