Contact Application Test

David Winterfeldt

2012


The DAO, Services, and REST Services all have a shared Spring Test context setup when the abstract test base for each module is extended. This will improve overall test performance since any setup by Spring will only be performed once for a suite of tests.

There is a contact-test module that is used to share abstract test base classes, constants used across layers, and any shared config. This is used instead of having each module generate it's own test artifact. When each there are a lot of test artifacts, inter-module dependencies can become more complicated.

1. Abstract Test Code

These are shared abstract base classes for tests in different modules to extend.

Abstract Code

The AbstractProfileTest sets up the main JUnit Spring test runner and sets the default Spring Active Profile to use the HSQL DB. All of the tests from each module extend this class.

Example 1. AbstractProfileTest

                    
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles= { HSQL })
public abstract class AbstractProfileTest {

    /**
     * Setup the security context before each test.
     */
    @Before
    public void setUp() {
        doInit();
    }

    /**
     * Clear the security context after each test.
     */
    @After
    public void tearDown() {
        SecurityContextHolder.clearContext();
    }

    /**
     * Set the default user on the security context.
     */
    protected abstract void doInit();

}
                    
                

Example 2. AbstractTransactionalProfileTest

The DAO and Service tests extend this abstract class. It extends AbstractProfileTest, sets up the Spring transactional test configuration, and also configures a default security context. The Spring transactional test configuration provides automatic transaction rollback as each individual test finishes. Having the security context set before each test is to reset it to the default in case an individual test made any changes to test different users.

                    
@TransactionConfiguration
@Transactional
public abstract class AbstractTransactionalProfileTest extends AbstractProfileTest {

    /**
     * Set the default user on the security context.
     */
    protected void doInit() {
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(DEFAULT_SECURITY_USER, DEFAULT_SECURITY_USER_PASSWORD));
    }

}