目的是,对于每个单元测试,系统地启动一个 tomcat 7 服务器,加载 spring 应用程序(最终删除/创建一个模式并在数据库中初始化它的数据)执行单元测试并停止 http 服务器。
使用 jetty 嵌入式服务器很容易找到示例
我没有找到正确的方法来配置嵌入式 tomcat 7 服务器以加载 spring 上下文
你能帮帮我吗?
项目结构是一个名为“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 打包应用程序时会自动执行测试。您也可以生成测试报告...最佳实践...