Я посмотрел на опубликованные ответы и подумал, что отправлю более полное решение, которое на самом деле демонстрирует, как проводить тестирование с использованием встроенного GlassFish и его плагина Apache Maven.
Я написал полный процесс на моем блоге Using GlassFish 3.1.1 Embedded with JUnit 4.x and HtmlUnit 2.x и разместил полный проект для загрузки на Bitbucket здесь: image-servlet
Я смотрел на другую должность на качестве сервлета изображения для JSP/JSF тегов, прежде чем я увидел это вопрос.Поэтому я объединил решение, которое я использовал с другого поста, с полной версией, проверенной модулем для этого сообщения.
Как проверить
Apache Maven имеет четко определенный жизненный цикл, который включает в себя test
. Я буду использовать его вместе с другим жизненным циклом, который называется integration-test
для реализации моего решения.
- Отключить стандартное тестирование жизненного цикла в плагине surefire.
- Добавить
integration-test
в качестве части исполнения верфи-плагина
- Добавить плагин GlassFish Maven к POM.
- Настройте GlassFish для выполнения во время жизненного цикла
integration-test
.
- Пробные испытания (интеграционные тесты).
GlassFish Плагин
Добавьте этот плагин как часть <build>
.
<plugin>
<groupId>org.glassfish</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<!-- This sets the path to use the war file we have built in the target directory -->
<app>target/${project.build.finalName}</app>
<port>8080</port>
<!-- This sets the context root, e.g. http://localhost:8080/test/ -->
<contextRoot>test</contextRoot>
<!-- This deletes the temporary files during GlassFish shutdown. -->
<autoDelete>true</autoDelete>
</configuration>
<executions>
<execution>
<id>start</id>
<!-- We implement the integration testing by setting up our GlassFish instance to start and deploy our application. -->
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
<goal>deploy</goal>
</goals>
</execution>
<execution>
<id>stop</id>
<!-- After integration testing we undeploy the application and shutdown GlassFish gracefully. -->
<phase>post-integration-test</phase>
<goals>
<goal>undeploy</goal>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
Surefire Плагин
Добавить/изменить плагин как часть <build>
.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<!-- We are skipping the default test lifecycle and will test later during integration-test -->
<configuration>
<skip>true</skip>
</configuration>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<!-- During the integration test we will execute surefire:test -->
<goal>test</goal>
</goals>
<configuration>
<!-- This enables the tests which were disabled previously. -->
<skip>false</skip>
</configuration>
</execution>
</executions>
</plugin>
HtmlUnit
Добавить интеграционные тесты, как на примере ниже.
@Test
public void badRequest() throws IOException {
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/test/images/");
final WebResponse response = page.getWebResponse();
assertEquals(400, response.getStatusCode());
assertEquals("An image name is required.", response.getStatusMessage());
webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(true);
webClient.closeAllWindows();
}
Я написал полный процесс на моем блоге Using GlassFish 3.1.1 Embedded with JUnit 4.x and HtmlUnit 2.x и разместил полный проект для загрузки на Bitbucket здесь: image-servlet
Если у вас есть какие-либо вопросы, пожалуйста, оставьте комментарий. Я думаю, что это один полный пример использования вами в качестве основы для любого тестирования, которое вы планируете использовать для сервлетов.
возможно дубликат [Unit-тестирования сервлетов] (http://stackoverflow.com/questions/53532/unit-testing- сервлеты) – Raedwald 2013-06-10 11:51:50