ServletContextをDIしているクラスをJUnitでテストするには...

ServletContextは、サーブレットコンテナに依存するため、通常、サーバーを起動しないと使用できない。

そこで、JUnit上から、Springで、ServletContextをDIしてるクラスをテストするため、ServletContextをモッククラス(MockServletContext)と置き換えるようにしました。


  • テスト対象クラス
import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;

@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public final class Target {

	@Autowired
	private ServletContext context;

	public void proc() {

	}
}
  • テストクラス
import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

public class TargetTest {

	private static XmlWebApplicationContext context;
	
	Target target;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		String[] contexts = new String[] { "classpath:WEB-INF/conf/application-context.xml" };
		context = new XmlWebApplicationContext();
		context.setConfigLocations(contexts);
		MockServletContext mockServletContext = new MockServletContext(
				"classpath:", new FileSystemResourceLoader());
		context.setServletContext(mockServletContext);
		context.refresh();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		target = (Target) context
				.getBean("target");
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testProc() {
		target.proc();
	}