IDEA 創(chuàng)建 Jersey 項目及增加單元測試的流程。
1. 創(chuàng)建 Jersey 項目
在 IDEA 中按以下步驟操作:New Project --> Maven --> Create from archetype --> org.glassfish.jersey.archetypes:jersey-quickstart-webapp --> jeresy-quickstart-webapp:2.29.1
。 如圖:
然后 Next
,填寫 GroupId 和 ArtifactId ,選擇項目路徑等等蠢挡,直到完成。
2. 配置 Run
在 IDEA 中按以下步驟操作:Run --> Edit Configurations --> "+" --> Tomcat Server --> Local --> Server --> Application server --> Configure...
。如圖:
注意晓避,HTTP port
需要設置為一個為被占用的端口簇捍,例如:如果 8080 端口已經(jīng)被其他應用占用,這里就可以換成 8081俏拱。如圖:
然后配置編譯文件的存放位置暑塑。 Deploymeng --> "+" --> Artifact... --> test:war exploded --> Edit Artifact --> Output directory
填寫存放目錄。
3. 運行項目
Run --> Run 'Tomcat'
打開瀏覽器即可看到效果锅必。
4. 添加單元測試
支持 JUnit 和 TestNG 兩種測試框架
使用 JUnit 測試框架:
在 pom.xml
中添加 container 依賴:
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
</dependency>
添加測試方法:
package jerseytest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.ws.rs.core.Application;
import static org.junit.Assert.assertEquals;
public class MyResourceTest extends JerseyTest {
@Override
protected Application configure() {
return new ResourceConfig(MyResource.class);
}
@Test
public void testGetIt() {
final String hello = target("myresource").request().get(String.class);
assertEquals("Got it!", hello);
}
}
使用 TestNG 測試框架:
在 pom.xml
中添加 container 和 TestNG 依賴:
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
添加測試方法:
package com.supermap.atlab;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTestNg;
import org.testng.annotations.Test;
import javax.ws.rs.core.Application;
import static org.testng.AssertJUnit.assertEquals;
public class MyResourceTest extends JerseyTestNg.ContainerPerClassTest {
@Override
protected Application configure() {
return new ResourceConfig(MyResource.class);
}
@Test
public void testGetIt() {
final String hello = target("myresource").request().get(String.class);
assertEquals("Got it!", hello);
}
}
更多信息請參閱文檔 Jersey Test Framework