Java Reference
In-Depth Information
The file defines the information used by the datasource to connect to your
database as well as a list of scripts to execute on startup. In this case, the HSQLDB connection
information is very straightforward, and you have two scripts to run on startup: schema-hsqldb.sql
creates the Spring Batch tables for you, and schema.sql creates the statement tables.
With the test environment configured, you can begin to write your first integration test. The next
section looks at how to write an integration test for TickerDao .
Writing an Integration Test
Writing an integration test with Spring is very simple. You need to do three things:
1. Tell Spring the location from which to load your context.
2. Extend AbstractTransactionalJUnit4SpringContextTests (yes, that really is the
name of the class) to get the transactional help that Spring provides.
3. Tell Spring what values to wire.
After you've done these three things, you can use your code just as if it was in your application. Let's
start by telling Spring the location from which to load your context. To do this, you use Spring's
@ContextConfiguration annotation at the class level. For your purposes, this annotation takes a single
attribute, location , which tells Spring where to find the test-context.xml file.
One of the main advantages of using the Spring testing infrastructure is the transaction benefits it
provides. It can be very helpful to be able to run a test in a transaction that rolls back after each test
method is executed. This way, your database begins and ends each test case in the exact same state. By
extending Spring's AbstractTransactionalJUnit4SpringContextTests class, you get that functionality
with no further work. Listing 12-11 shows the shell of the integration test with the context location
configured and the shell extending the correct class.
Listing 12-11. TickerDaoIntegrationTest Shell
package com.apress.springbatch.statement.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = {"/test-context.xml"})
public class TickerDaoIntegrationTest extends
AbstractTransactionalJUnit4SpringContextTests {
Now, because you're going to test TickerDao (the TickerDaoJdbc class, to be exact), you need Spring
to wire it up and inject it into your test so it's available. To do this, you use Spring's @Autowired
annotation to identify any class attribute that you want Spring to wire for you. Because all you need for
this test is for TickerDao itself to be wired, that is all you need to indicate to Spring.
The rest of an integration test with Spring is the same as it would be if it was a unit test. You prepare
any data required for the test, execute the code being tested, and finally use JUnit's assertions to validate
what happened. The code in Listing 12-12 tests the saving and retrieving of a ticker using TickerDao .
Search WWH ::

Custom Search