如何从jar运行测试用例

时间:2017-11-11 18:55:14

标签: java selenium selenium-webdriver

我创建了扩展TestCase的AppTest类。 如果我单独运行这个测试类,它会成功运行,但是当我尝试通过主类调用该测试类时,它会给我发现错误的课程

div

当我尝试使用另一个类的main方法调用AppTest时,它给出了我的错误:java.lang.ClassNotFoundException:user.login.creation.UserValidation.AppTest

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import junit.framework.TestCase;

/**
 * Unit test for simple App.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@Service
@ContextConfiguration
public class AppTest extends TestCase
{
    // Create WebDriver instance
    static WebDriver driver;
    static int count = 2;
    @Value("${configValue.url}")
    private String url;

    @Value("${configValue.makerList}")
    private String makerList;

    static Map < String, Object[] > testReport = new TreeMap < String, Object[] >();

    //Create blank workbook
    static XSSFWorkbook workbook = new XSSFWorkbook(); 
    //Create a blank sheet
    static XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
  //Create row object
    static XSSFRow row;

    public static String deleteApiStatus = "";

    @Before
    public void setUp() throws Exception {
        // Initialize the WebDriver instance using chrome and launch the web browser
        System.setProperty("webdriver.chrome.driver", "./Chrome/chromedriver.exe");
        driver = new ChromeDriver();
        // Open the application 
        driver.navigate().to(url);
        // Maximize the current window
        driver.manage().window().maximize();
    }
    @BeforeClass
    public static void init() throws Exception {
        testReport.put( "0", new Object[] {"SINK MIXER" });
        testReport.put( "1", new Object[] {"COMPANY NAME", "PHONE NO", "MOBILE NO", "FAX", "LOCATION" });
    }


    @Test
    public void checkCreatedUserValue() throws Exception {

         List<WebElement> month_menu = driver.findElements(By.xpath(".//div[@class='company']"));
            for (int i=0;i<1;i++) //month_menu.size()
            {
                WebElement element = month_menu.get(i);
                String contents = element.getAttribute("innerHTML");
                String[] url = contents.split(" ");
                contents = url[47];
                StringBuilder sb = new StringBuilder(contents);
                sb.delete(0,36);
                sb.deleteCharAt(sb.length()-1);

                System.out.println(sb.toString());
                String[] newUal = sb.toString().split("/");
                String contactUrl = "https://"+newUal[0]+".fm.alibaba.com/"+newUal[1];
                WebDriver newDriver = new ChromeDriver();
                newDriver.navigate().to(contactUrl);
                newDriver.manage().window().maximize();
                newDriver.findElement(By.className("contact-detail-mask")).click();
                newDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
                List<WebElement> elems = newDriver.findElements(By.xpath(".//li[@class='sc-hd-prefix2-tab-trigger']"));
                elems.get(0).click();

                WebElement iframe= newDriver.findElement(By.id("alibaba-login-box"));
                newDriver.switchTo().frame(iframe);
                WebElement elem = newDriver.findElement(By.id("fm-login-id"));
                elem.clear();
                elem.sendKeys("swagatpathade@gmail.com");
                elem = newDriver.findElement(By.id("fm-login-password"));
                elem.sendKeys("Test123");
                newDriver.findElement(By.id("fm-login-submit")).click();
                newDriver.switchTo().defaultContent();
                Thread.sleep(5000);
                newDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
                String companyName =  newDriver.findElement(By.className("company-name")).getText();
                String phone =  newDriver.findElement(By.cssSelector("dd[data-role='phone']")).getAttribute("innerText");
                String mobile =  newDriver.findElement(By.cssSelector("dd[data-role='mobile']")).getAttribute("innerText");
                String fax =  newDriver.findElement(By.cssSelector("dd[data-role='fax']")).getAttribute("innerText");
                List<WebElement> location = newDriver.findElements(By.xpath("//*[@id=\"site_content\"]/div[1]/div/div[2]/article/div/table/tbody/tr[2]/td[2]"));
                count++;
                String countNo =  Integer.toString(count);
                testReport.put(countNo, new Object[] {companyName, phone, mobile, fax, location.get(0).getText() });
                newDriver.quit();  
            }
    }

    @After
    public void tearDown() {
        // Quit the launched web browser
        driver.quit();
    }


    @Configuration
    @ComponentScan("user.login.creation.UserValidation")
    static class someConfig {

        // because @PropertySource doesnt work in annotation only land
        @Bean
        PropertyPlaceholderConfigurer propConfig() {
            PropertyPlaceholderConfigurer ppc =  new PropertyPlaceholderConfigurer();
            ppc.setLocation(new ClassPathResource("configValue.properties"));
            return ppc;
        }
    }

    @AfterClass
    public static void createReport(){

        //Iterate over data and write to sheet
          Set < String > keyid = testReport.keySet();
          int rowid = 0;
          for (String key : keyid)
          {
             row = spreadsheet.createRow(rowid++);
             Object [] objectArr = testReport.get(key);
             int cellid = 0;
             for (Object obj : objectArr)
             {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue((String)obj);
             }
          }
          //Write the workbook in file system
          FileOutputStream out;
        try {
            out = new FileOutputStream(new File("./ReportSheet.xlsx"));
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
          System.out.println("\n");
          System.out.println("----------------------------------------------------------------------------------------------------------------------");
          System.out.println("ReportSheet.xlsx created successfully.");
          System.out.println( "----------------------------------------------------------------------------------------------------------------------");
          System.out.println("\n");

          System.out.println("----------------------------------------------------------------------------------------------------------------------");
          System.out.println("Maven build completed. You can find detailed test case report in automatedTestReport folder present in current project structure.");
          System.out.println( "----------------------------------------------------------------------------------------------------------------------");
          System.out.println("\n");

          /*System.out.println("----------------------------------------------------------------------------------------------------------------------");
          System.out.println("You can also find the error screenshot occurred during the execution in screenshot folder of current project structure (if any).Test case report contain detailed discription about occurred error.");
          System.out.println( "-----------------------------------------------------------------------------------------------------------------------");
          System.out.println("\n");*/

    }
}

错误

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "setup!" );
        AppTest app = new AppTest();
        app.run();
    }
}

我想从main方法运行那些测试用例,有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

public static void main(String[] args) throws Exception {                    
       JUnitCore.main(
         "AppTest");            
}  

一旦出现错误就执行此主类,但继续执行以下步骤来创建jar:

Right click on project.
Go To Export.
Select Jar or Runnable Jar as per your use click on next.
Specify the main file name.
Click on Finish.  

从命令提示符执行命令以运行您的jar文件:

java -jar path-to-jar-file-with-name.jar  

如有任何疑虑,请与我联系。