目的は、単体テストごとにTomcat 7サーバーを体系的に起動し、Springアプリケーションをロードし(最終的にスキーマをドロップ/作成してデータベースにデータを初期化)、単体テストを実行し、httpサーバーを停止することです。
jetty組み込みサーバーでそれを行うためのサンプルを見つけるのは非常に簡単です
Spring コンテキストをロードするために、組み込みの tomcat 7 サーバーを構成する正しい方法が見つかり
ませんでした。
プロジェクト構造は、「myApp」という名前の標準の Maven webApp プロジェクトです。
src
+-main
+-java
+-webapp
+-static
+-WEB-INF
+-web.xml
+-applicationcontext.xml
target
+-myApp
+-webapp
+-static
+-WEB-INF
+-classes
抽象単体テスト:
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.apache.catalina.Context;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"applicationContext.xml"})
public abstract class AbstractMainHTTPTestCase
{
private int PORT;
private Tomcat tomcat;
private String appBase;
private String contextPath;
private String hostname;
private String baseDir;
public Client client;
public WebResource webResource;
public String response;
@Before
public final void setUp() throws Exception
{
this.PORT = 8081;
this.appBase = "src/main/webapp";
this.contextPath = "";
this.baseDir = ".";
this.hostname = "localhost";
this.tomcat = new Tomcat();
this.tomcat.setPort(this.PORT);
this.tomcat.setBaseDir(this.baseDir);
this.tomcat.getHost().setAppBase(this.appBase);
this.tomcat.setHostname(this.hostname);
Context ctx = this.tomcat.addWebapp(this.contextPath, this.appBase);
File contextFile = new File(this.appBase + "/WEB-INF/web.xml");
ctx.setConfigFile(contextFile.toURI().toURL());
this.tomcat.start();
this.tomcat.getServer().await();
}
@After
public final void tearDown() throws Exception
{
this.tomcat.stop();
}
}
URL をテストするための典型的なテスト クラス:
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sproutcore.sample.todos.AbstractMainHTTPTestCase;
public class MainControllerTest extends AbstractMainHTTPTestCase
{
private static final Logger LOG = LoggerFactory.getLogger(MainControllerTest.class);
@Test
public void staticTest() throws Exception
{
LOG.debug("HTTP TEST: staticTest");
this.response = this.webResource.path("/static/test.txt").get(String.class);
LOG.debug("staticTest response: {}", this.response);
assertNotNull("Static test shall be not null", this.response);
}
}
静的フォルダーは applicationcontext.xml で構成されます。
<!-- Handles HTTP GET requests for /static/** -->
<mvc:resources mapping="/static/**" location="/static/" />
この働き方では、最初に単体テストをコーディングし、データ単体テストを作成してから、アプリケーション機能をコーディングできます。アプリケーションをmavenでパッケージ化すると、テストが自動的に実行されます。テスト レポートも生成できます... ベスト プラクティス...