In order for the unit test to run a batch job, the framework must load the job’s ApplicationContext. Two annotations are used to trigger this:

@RunWith(SpringJUnit4ClassRunner.class): Indicates that the class should use Spring’s JUnit facilities.

@ContextConfiguration(locations = {...}): Indicates which XML files contain the ApplicationContext.

For example:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})
public class MyTest {

	@Autowired
	UnitService unitService;

	@Test
	public void test1(){
		UnitModel unitdto = new UnitModel();
		unitdto.setUnitCode("15524");
		UnitModel unitvo = unitService.loadOneUnit(unitdto);
		if(unitvo != null) {
			String unitName = unitvo.getUnitName();
			System.out.println(unitName);
		}
	}
}
 

If you are using annotations rather than XML files, then any class that you are unit testing that requires Spring dependency injection needs to be put into the @ContextConfiguration annotation.

For example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooManager.class)
class FooManagerTest {
    
    @Autowired
    FooManager fooManager;
} 

Now when you use fooManager in a unit test it will have have a Spring context setup for it.

If fooManager autowires in any beans then those bean’s classes also need to be in the @ContextConfiguration annotation. So if fooManager autowires in a FooReporter bean:

@ContextConfiguration(classes = {FooManager.class, FooReporter.class}) 

If the beans that fooManager autowires in contain state, then you will likely want to reset the state of those beans for each test. In that case you can add the @DirtiesContext annotation to your test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) 

If fooManager or any of its autowired beans reads Spring config then you need to add an initializers list to the @ContextConfiguration annotation, that contains the ConfigFileApplicationContextInitializer class:

@ContextConfiguration(classes = {FooManager.class, FooReporter.class}, initializers = ConfigFileApplicationContextInitializer.class) 

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *