2017-11-11 248 views
0

我創建了擴展TestCase的AppTest類。 如果我單獨運行這個測試類運行成功,但是當我嘗試調用通過主類,它給我的類上發現的錯誤如何從jar運行測試用例

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("[email protected]"); 
       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");*/ 

    } 
} 

該測試類,當我試圖使用的另一種主要方法AppTest調用類,它給我的錯誤是:拋出java.lang.ClassNotFoundException:user.login.creation.UserValidation.AppTest

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

錯誤

Exception in thread "main" java.lang.NoClassDefFoundError: user/login/creation/UserValidation/AppTest 
    at user.login.creation.UserValidation.App.main(App.java:12) 
Caused by: java.lang.ClassNotFoundException: user.login.creation.UserValidation.AppTest 
    at java.net.URLClassLoader.findClass(Unknown Source) 
    at java.lang.ClassLoader.loadClass(Unknown Source) 
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) 
    at java.lang.ClassLoader.loadClass(Unknown Source) 
    ... 1 more 

我想從主要方法運行測試用例,有什麼建議嗎?

+0

你如何包裝罐子?它在'src/main'文件夾中而不是測試? –

+0

@DarrenForsythe是它在主文件夾中,我的測試課程在測試文件夾中。 – Swagat

回答

0

你可以試試下面的代碼:

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

執行這個主類,一旦你可能會遇到錯誤,但與下面的步驟繼續創建罐子:

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 

讓我知道萬一有任何顧慮。