`
koen
  • 浏览: 81962 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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

阅读更多

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

 

先看代码:

 

/*
 * 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:

 

        <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>
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics