used by the custom test execution listener for loading test data from the Excel file. Note that the
dataSourceDatabaseTester bean was constructed using the dataSource bean defined for the testing
environment.
Implementing the Base Test Class
Listing 19-11 shows the abstract base class for service layer testing.
Listing 19-11. The AbstractServiceImplTest Class
package com.apress.prospring3.ch19.service.jpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import
org.junit.runner.RunWith;
import
org.springframework.test.context.ActiveProfiles;
import
org.springframework.test.context.ContextConfiguration;
import
org.springframework.test.context.TestExecutionListeners;
import
org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.apress.prospring3.ch19.test.config.ServiceTestConfig;
import com.apress.prospring3.ch19.test.listener.ServiceTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ServiceTestConfig.class})
@TestExecutionListeners({ServiceTestExecutionListener.class})
@ActiveProfiles("test")
public abstract class AbstractServiceImplTest extends
AbstractTransactionalJUnit4SpringContextTests {
@PersistenceContext
protected EntityManager em;
}
In Listing 19-11, the @RunWith annotation is the same as testing the controller class. The
@ContextConfiguration specifies that the ApplicationContext configuration should be loaded from the
ServiceTestConfig class. The @TestExecutionListeners annotation indicates that the
ServiceTestExecutionListener class should be used for intercepting the test case execution life cycle.
The @ActiveProfiles annotation specifies the profile to use. So, in this case, the dataSource bean defined
in the ServiceTestConfig class will be loaded, instead of the one defined in the datasource-tx-jpa.xml
file, since it belongs to the dev profile.
In addition, the class extends Spring's AbstractTransactionalJUnit4SpringContextTests class,
which is Spring's support for JUnit, with Spring's DI and transaction management mechanism in place.
Note that in Spring's testing environment, Spring will roll back the transaction upon execution of each
test method so that all database update operations will be rolled back. To control the rollback behavior,
you can use the @Rollback annotation at the method level.
Finally, within the abstract base class, the EntityManager is autowired, which can then be used
within test cases.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home