如何在 Java 中执行 Selenium 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18492668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:30:48  来源:igfitidea点击:

How to execute a Selenium test in Java

javaeclipseselenium

提问by Man Friday

So I used Selenium IDEto create a test case for some automation I want done. I want to be able to create some looping/flow control for this case so I figured I would need to export it out of Selenium IDE to something like Java (I'm most familiar with Java). I exported to Java/JUnit4/Web Driver. I think trying to execute the java file through Eclipsewould work best, although if someone knows something easier, let me know. Anyway, I have found NO GOOD EXPLANATION on how to execute this Java through Eclipse.

所以我使用Selenium IDE为我想要完成的一些自动化创建了一个测试用例。我希望能够为这种情况创建一些循环/流控制,所以我想我需要将它从 Selenium IDE 导出到 Java 之类的东西(我最熟悉 Java)。我导出到Java/JUnit4/Web Driver。我认为尝试通过Eclipse执行 java 文件效果最好,但如果有人知道更简单的事情,请告诉我。无论如何,我没有找到关于如何通过 Eclipse 执行这个 Java 的好解释。

Most things I read tell me to make sure my Build Path libraries includes the Selenium Standalone Server. Virtually all things I read tell me to use the Selenium Remote Control. However, I thought the RC was depreciated, and I am wondering if there is anyway to make it work with the more recent Web Driver stuff I downloaded from Selenium. Also, most things I read tell me I need to use public static void main(), which is a little awkward because I don't know how to alter the code the exported selenium gives me (obviously I can't just paste it all in the main method).

我读到的大部分内容都告诉我要确保我的 Build Path 库包含Selenium Standalone Server。几乎我读过的所有内容都告诉我要使用 Selenium 遥控器。但是,我认为 RC 折旧了,我想知道是否有办法让它与我从 Selenium 下载的更新的 Web 驱动程序一起使用。另外,我读到的大多数内容都告诉我我需要使用public static void main(),这有点尴尬,因为我不知道如何更改导出的 selenium 给我的代码(显然我不能只是粘贴所有内容在主要方法中)。

If anyone could walk me through from exportation of Selenium to Java to executing the code, I will be forever in your debt.

如果有人能引导我完成从 Selenium 到 Java 的导出到执行代码的过程,我将永远欠你的债。

The code Selenium gives me: package com.example.tests;

Selenium 给我的代码:包 com.example.tests;

package com.rackspace;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class RackspaceContactAutomation {
   private WebDriver driver;
   private String baseUrl;
   private boolean acceptNextAlert = true;
   private StringBuffer verificationErrors = new StringBuffer();

   @Before
   public void setUp() throws Exception {
      driver = new FirefoxDriver();
      baseUrl = "https://cp.rackspace.com/Exchange/Mail/Contacts/List.aspx?selectedDomain=blahblahblah.com";
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
   }

   @Test
   public void testContactAutomationJava() throws Exception {
      driver.get(baseUrl + "/Exchange/Mail/Contacts/List.aspx?selectedDomain=blahblahblah.com");
      driver.findElement(By.linkText("Mr. Man")).click();
      driver.findElement(By.linkText("Contact Information")).click();
      new Select(driver.findElement(By.id("PhoneNumberType"))).selectByVisibleText("Mobile");
      driver.findElement(By.id("MobilePhone")).sendKeys("999-999-9999");
      new Select(driver.findElement(By.id("PhoneNumberType"))).selectByVisibleText("Fax");
      driver.findElement(By.id("Fax")).sendKeys("999-999-9999");
      driver.findElement(By.cssSelector("button.primary")).click();
   }

   @After
   public void tearDown() throws Exception {
      driver.quit();
      String verificationErrorString = verificationErrors.toString();
      if (!"".equals(verificationErrorString)) {
         fail(verificationErrorString);
      }
   }

   private boolean isElementPresent(By by) {
      try {
         driver.findElement(by);
         return true;
      } catch (NoSuchElementException e) {
         return false;
      }
   }

   private boolean isAlertPresent() {
      try {
         driver.switchTo().alert();
         return true;
      } catch (NoAlertPresentException e) {
         return false;
      }
   }

   private String closeAlertAndGetItsText() {
      try {
         Alert alert = driver.switchTo().alert();
         String alertText = alert.getText();
         if (acceptNextAlert) {
            alert.accept();
         } else {
            alert.dismiss();
         }
         return alertText;
      } finally {
         acceptNextAlert = true;
      }
   }
}

This gives me 4 errors (3 for the annotations, which I could just delete, and one for failin the tearDown()method. It's not the errors I'm concerned about so much the how do I make this code actually execute?

这给了我4个错误(3注释,这我可以删除,一个是failtearDown()方法,这不是我关心的误差这么多我怎么让这段代码实际执行?

Thanks!

谢谢!

回答by James Dunn

A good way to run Selenium Java code in Eclipse is to run them as JUnit tests.

在 Eclipse 中运行 Selenium Java 代码的一个好方法是将它们作为JUnit 测试运行。

1. Create a Maven Project in your Eclipse.
If you haven't done this before, see:

1. 在 Eclipse 中创建一个 Maven 项目。
如果您以前没有这样做过,请参阅:

2. Add the following dependencies to your pom.xml file:

2. 将以下依赖项添加到您的 pom.xml 文件中:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.7</version>
    <scope>test</scope>
</dependency>    
<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.25.0</version>           
</dependency> ?? 
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>2.33.0</version>
</dependency> 
<dependency><groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-server</artifactId>
    <version>2.25.0</version>    
</dependency>

3. Copy your exported Java file into the Maven Project.

3. 将导出的 Java 文件复制到 Maven 项目中。

4. Add the following imports to the file:

4. 将以下导入添加到文件中:

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

5. Run the Java file as a JUnit test, like so:

5. 将 Java 文件作为 JUnit 测试运行,如下所示:

Example from my Eclipse (Version is Kepler)

来自我的 Eclipse 的示例(版本是 Kepler)

回答by paul jay

My answer to converting selenium in to a j unit test, is quite simple.

我将 selenium 转换为 j 单元测试的答案非常简单。

1st you need to set up the code in the perspective workbench the use the editor by clicking on in the tool bar >go to shown in>then press on one of these editor > you see Java editor or window editor and so on, this will convert your code. then press go back to the class and highlight it, right click on the mouse and run it as Java application. you should be able to see your design/and source code. anymore questions

1st 您需要在透视工作台中设置代码,通过单击工具栏中的使用编辑器>转到显示>然后按这些编辑器之一>您会看到 Java 编辑器或窗口编辑器等,这将转换您的代码。然后按返回类并突出显示它,右键单击鼠标并将其作为Java应用程序运行。您应该能够看到您的设计/和源代码。再问

回答by bitiotek

The previous answer are all legitimate. But to run directly from your eclipse you need do some modifications to your code. You dont need public void main to run a junit code. So Here are the steps to enable you to just copy over the code and paste it in eclipse and run as JUnit test:

之前的答案都是合法的。但是要直接从 Eclipse 运行,您需要对代码进行一些修改。您不需要 public void main 来运行 junit 代码。因此,以下是使您能够复制代码并将其粘贴到 eclipse 中并作为 JUnit 测试运行的步骤:

  1. Install JUnit in eclipse->Help->eclipse market place-> search for JUnit and install it, restart eclipse.

  2. Create a project in eclipse and a new package, then create a new class with the same name as your selenium IDE exported code, delete everything except the package line.

  3. copy and paste the code from selenium IDE to that class, remove the package line.

  4. Right click in your code area and run as JUnit test.

  1. 在eclipse->Help->eclipse market place->搜索JUnit安装JUnit,重启eclipse。

  2. 在 eclipse 中创建一个项目和一个新包,然后创建一个与您的 selenium IDE 导出代码同名的新类,删除除包行之外的所有内容。

  3. 将 selenium IDE 中的代码复制并粘贴到该类中,删除 package 行。

  4. 右键单击您的代码区域并作为 JUnit 测试运行。