我已经使用Java EE 7提供的api实现了一个WebSocket.此外,我已经实现了一个请求我的WebSocket没有任何问题的客户端.为了确保在执行某些代码更改时这仍然有效,我想实现测试,这些测试也可以在构建服务器上运行,例如Jenkins CI,而不仅仅是在本地.我正在使用maven.
这是我的服务器端点:
import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@ApplicationScoped
@ServerEndpoint("/example")
public class WebSocket {
private final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
@OnOpen
public void open(Session session) {
sessions.add(session);
}
@OnClose
public void close(Session session) {
sessions.remove(session);
}
@OnError
public void onError(Throwable error) {
//TODO do something
}
@OnMessage
public void handleMessage(String message, Session session) throws IOException {
session.getBasicRemote().sendText("Hello "+message+"!");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的客户端端点:
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
@ClientEndpoint …Run Code Online (Sandbox Code Playgroud) 我在Java(Maven)Web项目中有两种测试:使用嵌入式Tomcat 7服务器进行"正常"单元测试和集成测试,使用Selenium进行Jenkins上的自动GUI测试.所有测试都使用JUnit进行注释@Test,正常测试以"Test.java"结束,而集成测试以"IntegrationTest.java"结束.所有测试类都位于src/test/java中
我通常使用构建我的项目mvn clean verify,而我的相关部分pom.xml启动tomcat服务器并相应地拆分测试类别如下所示:
<!-- For front-end testing -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<uriEncoding>UTF-8</uriEncoding>
<additionalConfigFilesDir>${basedir}/conf</additionalConfigFilesDir>
<contextFile>${basedir}/src/test/resources/context.xml</contextFile>
</configuration>
<executions>
<execution>
<id>start-tomcat</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run-war-only</goal>
</goals>
<configuration>
<fork>true</fork>
<port>9090</port>
</configuration>
</execution>
<execution>
<id>stop-tomcat</id>
<phase>post-integration-test</phase>
<goals>
<goal>shutdown</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.16</version>
<configuration>
<includes>
<include>**/*IntegrationTest*</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
Run Code Online (Sandbox Code Playgroud)
这个过程工作正常,除非我想在eclipse中运行我的测试,我通常右键单击我的项目 - >运行为 - > JUnit测试.通过选择此选项,可以运行所有测试(包括集成测试).在这种情况下,集成测试失败,因为Tomcat没有运行(它只在Maven的 …