Gangmax Blog

在unit test代码中控制embedded glassfish的启动

Migarated from here at ‘2012-06-04 17:16:25’.

以前做的一个例子,记录在这里作为备忘。

先看代码: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.test.standby;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import org.glassfish.embed.GlassFish;
import org.glassfish.embed.ScatteredWar;
import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author gang
*/
public class AppTest
{
private final String NAME = "AppTest";

@Test
public void testServlet() throws Exception
{
int port = 9999;
GlassFish glassfish = newGlassFish(port);
URL url = new URL("http://localhost:" + port + "/" + NAME + "/SimpleServlet");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
assertEquals("Wow, I'm embedded!", br.readLine());
glassfish.stop();
}

private GlassFish newGlassFish(int port) throws Exception
{
GlassFish glassfish = new GlassFish(port);
ScatteredWar war = new ScatteredWar(NAME, new File("src/main/resources"), new File("src/main/resources/WEB-INF/web.xml"), Collections.singleton(new File("target/classes").toURI().toURL()));
glassfish.deploy(war);
System.out.println("Ready ...");
return glassfish;
}
}

如果是使用maven,要运行以上代码,需要在pom.xml中加入如下的dependency:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.glassfish.embedded</groupId>
<artifactId>gf-embedded-api</artifactId>
<version>1.0-alpha-4</version>
</dependency>
<dependency>
<groupId>org.glassfish.distributions</groupId>
<artifactId>web-all</artifactId>
<version>10.0-build-20080430</version>
</dependency>

Comments