Jakob Nielsen
Jakob Nielsen

Reputation: 5198

Where to instantiate context.xml in Test Environment

We are using Spring Framework (XML Version) 4.0.5.RELAESE in our Java project. In our application the context.xml is instantiated at the begin of the application start, and provides every properties via dependecy injection.

Now I am wondering what is the best (and commonly used) strategy on where to instantiate it in the test environment. (We have some Unit, Integration and System tests who at least need the databaseBaseConnector bean provided in the context.xml,)

I thought about making an abstract class which every test extends from, but in this case it would be newly instantiated before every test. I would like to a have a solution similiar to the main application, where the context is only instantiated one time, and everything else needed is set via dependency injection.

Researching this topic didn`t help much yet, so I decided to ask the question.

Upvotes: 1

Views: 73

Answers (1)

Ralph
Ralph

Reputation: 120881

Spring comes with an SpringJUnit4ClassRunner and a @ContextConfiguration -annotation. If you use them, then spring will reuse the same Spring Context in different tests.

So a Spring test class can look like this:

package com.queomedia;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
//@Transactional
@ContextConfiguration(SpringTestContext.APPLICATION)
public class SpringContextTest {

    @Autowire
    private ApplicationContext applicationContext;

    //Test that the spring context can been loaded
    @Test
    public void testSpringContextLoad() {
        Assert.assertNotNull("application context expected", this.applicationContext);
    }
}

Upvotes: 1

Related Questions