Getting an error as while reading a JSON file using TestNG DataProviders in Selenium.
Error:
class com.google.gson.JsonObject cannot be cast to class org.json.simple.JSONObject (com.google.gson.JsonObject and org.json.simple.JSONObject are in unnamed module of loader 'app')
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.google.gson.JsonParser;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataDrivenTest_json {
WebDriver driver;
@BeforeClass
void setUp() { /* to set up chromedriver */
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.MILLISECONDS);
}
@Test(dataProvider="dp") /* using dataproviders*/
void login(String data) {
String list[] = data.split(",");
driver.get("some website url");
driver.findElement(By.cssSelector("[id='Email']")).sendKeys(list[0]);//username
driver.findElement(By.cssSelector("[id='Password']")).sendKeys(list[1]);//password
driver.findElement(By.cssSelector("[type='submit']")).click();
}
@DataProvider(name="dp")
public String[] readJson() throws IOException{
@SuppressWarnings("deprecation")
JsonParser jsonparser = new JsonParser();
FileReader reader =new FileReader("C:\\Users\\dell\\eclipse-workspace-
photon\\ExcelDriven\\src\\test\\java\\Testdata.json");
@SuppressWarnings("deprecation")
Object obj = jsonparser.parse(reader); //java object
JSONObject userLoginsJsonObj = (JSONObject)obj;
JSONArray userLoginsArray =(JSONArray)userLoginsJsonObj.get("userLogins");
String array[] = new String[userLoginsArray.size()];
for(int i=0; i<userLoginsArray.size();i++) {
JSONObject users = (JSONObject)userLoginsArray.get(i);
String username = (String)users.get("username");
String password = (String)users.get("password");
array[i] = username+","+password;
}
return array;
}
@AfterClass
void tearDown() { //close driver
driver.close();
}
}
/*My MavenProject has testng included and pom.xml file has 'com.googlecode.json-simple' dependency added.Still the above error is visible in console.*/
You import
class org.json.simple.JSONObject
while you need to importcom.google.gson.JsonObject
. You cannot just cast an object to any class even if that class has the same name. The package of the class also matters.