How to run test case from jar

Viewed 3573

I created AppTest class which extends TestCase. If I run this test class individually it runs successfully but when i try to call that test class through main class it's giving me class on found error

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");*/

    }
}

And when I tried to call the AppTest using main method of another class, it's giving me error as : 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();
    }
}

Error

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

I want to run that test cases from the main method, any suggestions ?

1 Answers

You can try below code:

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

Execute this main class once you may get the error but proceed with the below steps to create 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.  

From command prompt execute the command to run your jar file:

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

Let me know in case of any concerns.

Related