如何正确配置Selenium Maven插件以与Xvfb配合工作以运行无头浏览器

10

背景:
我正在使用selenium-server-2.25.0和J-Unit 4配合使用,运行一些关于我的GWT应用的UI测试场景。在我的IDE(Netbeans 7.2)中,我可以右键单击我的项目,选择“Test”,然后看到Firefox窗口(正常情况下)弹出,Selenium测试按预期运行。从命令行中,我也可以运行mvn integration-test并看到相同结果。

目标:
我试图让这些测试在Xvfb显示屏上无头运行,但我似乎在用Maven时遇到了问题。我可以手动运行export display=:2(:2是我的Xvfb显示屏),然后测试成功在隐形显示器上运行。

问题:
当我在我的pom.xml文件中包含此处的完整<plugin>条目并运行mvn integration-test时,似乎什么都没有改变。我仍然看到Windows弹出窗口,并且测试在Xvfb显示屏上运行。如果我将其删除并重新运行,则会得到相同的结果。但是,当我将阶段从pre-integration-test更改为qwertyasdf时,Maven会抱怨无效的生命周期阶段 - 因此我知道它并没有完全忽略它,而且我正在编辑相应的pom.xml。

谢谢!

1个回答

8
原来,“start-server”和“stop-server”目标是用于启动/停止SeleniumRC服务器的。这不是我想要的,因为我的所有测试都使用WebDriver API。
显然,在pom中,“xvfb”目标在指定的生命周期阶段确实启动了Xvfb会话——我想我以前没看到它。在其配置中,您可以指定写入一个属性文件,详细说明Xvfb正在运行的显示器。在Java代码中,可以读取此文件并将值传递给创建WebDriver时使用的FirefoxBinary。
相关的pom.xml部分如下:
<properties>
    <displayProps>target/selenium/display.properties</displayProps>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <systemPropertyVariables>
                    <display.props>${displayProps}</display.props>
                </systemPropertyVariables>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>selenium-maven-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <id>xvfb</id>
                    <phase>test-compile</phase>
                    <goals>
                        <goal>xvfb</goal>
                    </goals>
                    <configuration>
                        <displayPropertiesFile>${displayProps}</displayPropertiesFile>
                    </configuration>
                </execution> 
            </executions>  
        </plugin>
    </plugins>
</build>

这将在第一个可用的显示器(:20或更高)上启动Xvfb,并将该值写入属性文件中,我稍后会在我的Java代码中读取和使用。

String xvfbPropsFile = System.getProperty("display.props");

FirefoxBinary ffox = new FirefoxBinary();
ffox.setEnvironmentProperty("DISPLAY", /*read value from xvfbPropsFile*/);
WebDriver driver = new FirefoxDriver(ffox);

现在,驱动程序将控制在适当显示器上启动的Firefox实例。大功告成!

1
请展示文件 target/selenium/display.properties 的内容。 - Yu Jiaao
也许有人知道如何通过Maven插件将分辨率配置传递给Xvfb?我需要获得类似于带参数的命令行执行结果:Xvfb:0 -ac -screen 0 1024x768x24& - alwi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接