I am trying to read data from excel using apache poi with testng data provider but testng is skipping my test method.
Below is the error am getting
SKIPPED: VerifyLoanDetails
java.lang.RuntimeException: java.lang.NullPointerException
Caused by: java.lang.NullPointerException at com.seleniumhybrid.utils.ExcelUtil.getTestdata(ExcelUtil.java:62) at com.seleniumdata.zmartano.LoanDetails.getdata(LoanDetails.java:50)
Below is my class to read data from excel
public class ExcelUtil{
static Workbook book;
static Sheet sheet;
public static String Testdata_sheet = Constants.path_TestData;
public static Object [][] getTestdata(String sheetname) {
FileInputStream file = null;
try{
file = new FileInputStream(Testdata_sheet);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
}
catch(InvalidFormatException e ) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object [][]data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i=0;i<sheet.getLastRowNum();i++) {
for(int k=0;k<sheet.getRow(0).getLastCellNum();k++) {
data[i][k]= sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
}
below is my test class to acess the data
public class LoanDetails extends Configreader{
WebDriver driver;
#BeforeTest
public void beforetest() throws Exception {
driver = Browser.GetBrowser();
}
#Test(dataProvider = "getdata")
public void VerifyLoanDetails(String username) throws Exception {
driver.findElement(By.xpath(pro.getProperty("account_xpath"))).click();
driver.findElement(By.xpath(pro.getProperty("username_id"))).sendKeys(username);
}
#DataProvider
public Object[][] getdata(){
Object data [][] = ExcelUtil.getTestdata("credentials");
return data;
}
}
Related
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelUtils {
private XSSFSheet ExcelWSheet;
private XSSFWorkbook ExcelWBook;
//Constructor to connect to the Excel with sheetname and Path
public Excelutils(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to set the rowcount of the excel.
public int excel_get_rows() throws Exception {
try {
return ExcelWSheet.getPhysicalNumberOfRows();
} catch (Exception e) {
throw (e);
}
}
//This method to get the data and get the value as number.
public double getCellDataasnumber(int RowNum, int ColNum) throws Exception {
try {
double CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue();
System.out.println("The value of CellData " + CellData);
return CellData;
} catch (Exception e) {
return 000.00;
}
}
}
And in Main function i am calling
import Utils.ExcelUtils;
public class getInt extends OpenDriver {
#Test
public void getInt() throws Exception {
ExcelUtils TestData = new ExcelUtils("D:\\Selenium Automation\\TestData\\user.xlsx",
"User");
driver = LaunchBrowser();
driver.findElement(By.xpath("//input[#name='capacity']")).sendKeys(TestData.getCellDataasnumber(1, 3));
}
}
here i have created a excelutils and defined all my functions overthere
in main i have used excelUtils and passing value
I am getting error "The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (int)"
TestData.getCellDataasnumber(1, 3) will get number 25 from excel sheet.
tried, error not fixing
How can i fix this error
Just as the error says, you need a CharSequence as the parameter of the sendKeys method, instead of an int:
The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (int)
This means that you have to convert the int to a CharSequence. In practice, the simplest way to get a CharSequence is to create a String, so the solution is to convert the int to a String. You can achieve this in the following way:
String.valueOf(TestData.getCellDataasnumber(1, 3))
This is my Spring Boot Application.
when i run the main method always a null pointer exception is thrown.
I have no idea why the #Autowired JsonReaderService is null. As i define it as component.
It is a sub folder in the project src folder so the Main Method is above the source folder. So spring should scan it correctly??
I have also a test method which works just fine.
#SpringBootApplication
public class DemoApplication {
#Autowired
private JsonReaderService jsonReaderService;
private static JsonReaderService stat_jsonReaderService;
static Logger logger = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) throws IOException {
String textFileName = scanFileName();
Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + textFileName));
// This line is always null pointer exception. The #autowired Annotation don't work with my JsonReaderService????? WHY
List<EventDataJson> jsonReaderServicesList = stat_jsonReaderService.readEventDataFromJson(reader);
stat_jsonReaderService.mappingToDatabase(jsonReaderServicesList);
}
public static String scanFileName() {
logger.info("Scanning keyboard input");
System.out.println("enter a file to scan");
Scanner scanInput = new Scanner(System.in);
String text = scanInput.nextLine();
logger.info("successful keyboard input was : " + text);
return text;
}
#PostConstruct
public void init() {
logger.info("initializing Demo Application");
stat_jsonReaderService = jsonReaderService;
}
}
Here i have the class which uses the repository #Autowired to save some Entity but i get always a nullpointer exception in the line repository.save(...)
#Component
public class JsonReaderService {
static Logger logger = LoggerFactory.getLogger(DemoApplication.class);
#Autowired
EventDataRepository repository;
private Reader reader;
private List<EventDataJson> eventDataList;
#Autowired
public JsonReaderService(){}
public List<EventDataJson> readEventDataFromJson(Reader reader) throws IOException {
try {
logger.info("parsing event data from json started");
Gson gson = new Gson();
EventDataJson[] eventData = gson.fromJson(reader, EventDataJson[].class);
eventDataList = Arrays.asList(eventData);
reader.close();
} catch (IOException e) {
logger.error("Error while reading the json file");
e.printStackTrace();
}
logger.info("parsing json eventData successful finished");
return eventDataList;
}
public Boolean mappingToDatabase(List<EventDataJson> eventDataList) {
logger.info("mapping from json to database eventData started ...");
Set<String> idList = eventDataList.stream().map(EventDataJson::getId).collect(Collectors.toSet());
for (String id : idList
) {
Stream<EventDataJson> filteredEventDataList1 = eventDataList.stream().filter((item) -> item.getId().equals(id));
Stream<EventDataJson> filteredEventDataList0 = eventDataList.stream().filter((item) -> item.getId().equals(id));
EventDataJson startedEvent = filteredEventDataList1.filter((item) -> item.getState().equals("STARTED")).findAny().orElse(null);
EventDataJson finishedEvent = filteredEventDataList0.filter((item) -> item.getState().equals("FINISHED")).findAny().orElse(null);
long duration0 = finishedEvent.getTimestamp() - startedEvent.getTimestamp();
Boolean alert;
if (duration0 > 4) {
alert = true;
} else {
alert = false;
}
try {
this.repository.save(new EventDataDb(id, duration0, startedEvent.getType(), startedEvent.getHost(), alert));
logger.info("mapping to Database Repository action successful");
} catch (Exception e) {
logger.error("Exception in database mapping occurred");
e.printStackTrace();
return false;
}
}
return true;
}
}
Repository with Annotation
#Repository
public interface EventDataRepository extends JpaRepository<EventDataDb, String> {
EventDataDb findAllById(String id);
}
Test case works just fine with #autowired Annotation i Don't know why it don't work in the main method. Is it because it is static?
#Autowired
private EventDataRepository repository;
#Autowired
private JsonReaderService jReader;
#Test
public void whenParseJson_thenTransform_and_save_to_db() throws IOException {
BufferedReader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + "logfile.txt"));
List<EventDataJson> eventDataList1 = jReader.readEventDataFromJson(reader);
if (jReader.mappingToDatabase(eventDataList1)) {
EventDataDb eventDataFromDb = this.repository.findAllById("scsmbstgra");
Assertions.assertTrue(eventDataFromDb.getType().equals("APPLICATION_LOG"));
Assertions.assertTrue(eventDataFromDb.getHost().equals("12345"));
Assertions.assertTrue(eventDataFromDb.getAlert().equals(true));
Assertions.assertTrue(eventDataFromDb.getDuration() == 5);
logger.info("Assert successfully accomplished");
} else
logger.error("Could not persist eventData to DB Error");
}
Stack Trace
`Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.NullPointerException
at com.creditsuisse.demo.DemoApplication.main(DemoApplication.java:33)
... 5 more`
You need to run SpringApplication.run() because this method starts whole Spring Framework. Since you don't have it in your code, the beans are not autowired and JsonReaderService is null. You can do the following in your Application.java. Also, since this involves taking input from the CLI why not use CommandLineRunner as follows:
#SpringBootApplication
public class DemoApplication
implements CommandLineRunner {
#Autowired
private JsonReaderService jsonReaderService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) {
String textFileName = scanFileName();
Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + textFileName));
List<EventDataJson> jsonReaderServicesList = stat_jsonReaderService.readEventDataFromJson(reader);
jsonReaderService.mappingToDatabase(jsonReaderServicesList);
}
}
I'm getting NullPointerException upon passing a .xlsb file to a method. It seems that file is not getting selected but the file exists in that folder. Please advise
public class readxlsb {
public static void main(String[] args) throws Exception {
try {
String fileName1 ="C:\\abc\\TULDUBINV_EX_10768148_1.xlsb";
com.smartxls.WorkBook wb = new com.smartxls.WorkBook();
System.out.println(wb);
wb.readXLSB(fileName1);
System.out.println(wb);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The constructor of the API have the following methods:
public void readXLSB(String filename) throws Exception {
this.a.q(filename);
}
public void readXLSB(InputStream in) throws Exception {
this.a.d(in);
}
public void readXLSB(InputStream in, String pass) throws Exception {
this.a.a(in, pass);
}
Why not to use jxl.Workbook, it's much easier and comprehensive. I have worked with jxl and highly rely on it. Use like-Workbook workBook = Workbook.getWorkbook(new File("C:\\abc\\TULDUBINV_EX_10768148_1.xlsb"));
Sheet sheet = workBook.getSheet(0);
I have to write some dao tests for project where I want to:
create DDL schema from database (MySQL);
create tables in another test database in memory (H2);
insеrt some data to database;
select the just inserted item;
check some data from this item.
This is my test:
public class BridgeDBTest {
private static String JDBC_DRIVER;
private static String JDBC_URL;
private static String USER;
private static String PSWD;
private static final Logger logger = LoggerFactory.getLogger(BridgeDBTest.class);
#BeforeGroups(groups = "bridgeDB")
public void init(){
try {
JDBC_DRIVER = org.h2.Driver.class.getName();
JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
USER = "root";
PSWD = "";
new HibernateTestUtil().setDialect("org.hibernate.dialect.HSQLDialect")
.translateCreateDllToOutputStream(new FileOutputStream(new File("src/test/resources/createSchema.sql")));
RunScript.execute(JDBC_URL, USER, PSWD, "src/test/resources/createSchema.sql", Charset.forName("UTF8"), false);
insertDataset(readDataSet());
}
catch (Exception expt) {
expt.printStackTrace();
logger.error("!!!" + expt);
throw new RuntimeException(expt.getMessage());
}
}
#Test(groups = "bridgeDB")
public void getItem(){
BridgeDAOImpl dao = new BridgeDAOImpl();
dao.setSessionFactory(new HibernateTestUtil().getSessionFactory());
try {
Bridge bridge = dao.get(1L);
assert(bridge.getName().equals("TEST-CN-DEVBOX01"));
} catch (ServiceException e) {
e.printStackTrace();
}
}
#AfterGroups(groups = "bridgeDB")
public void dropTables(){
try {
new HibernateTestUtil().setDialect("org.hibernate.dialect.HSQLDialect")
.translateDropDllToOutputStream(new FileOutputStream(new File("src/test/resources/dropSchema.sql")));
}
catch (Exception expt) {
expt.printStackTrace();
logger.error("!!!" + expt);
throw new RuntimeException(expt.getMessage());
}
}
private IDataSet readDataSet() throws Exception{
return new FlatXmlDataSetBuilder().build(new File("src/test/resources/datasetForTest.xml"));
}
private void insertDataset(IDataSet dataSet) throws Exception{
IDatabaseTester databaseTester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PSWD);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setDataSet(dataSet);
databaseTester.onSetup();
}
}
BridgeDAOImplused class HibernateUtilfrom src/main/..., but I need to use my class HibernateTestUtil from src/test/.... It's modified HibernateUtil fitted for my test (there I set parameters for Configuration class).
BridgeDAOImpl (See 5 line in try block):
public class BridgeDAOImpl extends GenericDAOImpl<Bridge, Long> implements BridgeDAO {
//...
public SearchResult<Bridge> list(int from, int limit, String filter, String order, Long authId) throws ServiceException {
SearchResult<Bridge> results = null;
Search search = new Search(Bridge.class);
Session session = getSessionFactory().getCurrentSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
search.setFirstResult(from);
search.setMaxResults(limit);
HibernateUtil.buildSearch(filter, order, search, aliases);
results = searchAndCount(search);
transaction.commit();
}
catch (Exception expt) {
logger.error("!!!", expt);
if (transaction != null) {
transaction.rollback();
}
throw new ServiceException(expt.getMessage());
}
finally {
// session.close();
}
return results;
}
//...
}
How I can test my dao without modifying it?
Please suggest me how to sent 3 users in 3 browsers for this field
driver.findElement(By.id(PropertiesConfiguration.getMyProperty("PinTextfield"))).sendKeys(PropertiesConfiguration.getMyProperty("user"));
// main class
public class TestHRWW {`main class`
protected WebDriver driver;
#Parameters("browser")`parameter for browser initialization`
#BeforeClass
public void setup(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("iexplorer")) {
System.setProperty("webdriver.ie.driver","Drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver","Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
driver.manage().window().maximize();
}
#BeforeMethod
public void open() {
driver.get("http://www.myhrasiapacific.com/");
}
#AfterClass
public void teardown() {
try {
driver.quit();
} catch (Exception e) {
driver = null;
}
}
// sub class
public class Login extends TestHRWW {`sub class`
String x;
static Logger logger = Logger.getLogger(Login.class.getName());
#Test
public void ClickLogon(WebDriver driver) throws InterruptedException, IOException {
driver.findElement(`enter code here`
By.id(PropertiesConfiguration.getMyProperty("logonbutton")))
.click();
Thread.sleep(2000);
// here i need to sent 3 differt users credentials
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("PinTextfield")))
.sendKeys(PropertiesConfiguration.getMyProperty("user"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration
.getMyProperty("passwordTextfield"))).sendKeys(
PropertiesConfiguration.getMyProperty("password"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("loginbutton")))
.click();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
}
You shall use TestNG #DataProvider to pass username & passwords
your login method will be like
#Test(dataProvider="dataForLogin")
public void ClickLogon(String userName,String password) {
}
#DataProvider(name="dataForLogin")
public static Object[][] prepareDataForLogin(){
// preparation of login data
}
If you are using QAF then you don't need to manually parse your json data and get rid from data provider class.
public class tDataHelper {
private static List<String> studentsToCreate = new ArrayList<String>();
static void parseData() throws Exception {
studentsToCreate.add("user1");
studentsToCreate.add("user2");
studentsToCreate.add("user3");
}
#DataProvider
public static Object[][] createStudents() {
Object[][] objArray = new Object[studentsToCreate.size()][];
for (int i = 0; i < studentsToCreate.size(); i++) {
objArray[i] = new Object[1];
objArray[i][0] = studentsToCreate.get(i);
}
return objArray;
}
}
public class testStudents {
private static tDataHelper helper = new tDataHelper();
#BeforeClass
public void setup() throws Exception {
tDataHelper.parseData();
}
#Test(dataProvider = "createStudents", dataProviderClass = tDataHelper.class)
public void testCreateStudents(String studentsToCreate) {
System.out.println(studentsToCreate);
}
}
QAF Test Data Driven