I want to inherit the remotewebdriver from my BaseTest class so all my tests in another class can inherit the webdriver. Currently I only have it implemented in my 2nd class, I can do this quite easily if I am creating the tests locally, but we're utilizing a tool "CrossBrowserTesting" in order to scale our tests. Anyone have any ideas how this would look syntactically?
My attempts to inherit it from the BaseTest class haven't been panning out. It's not the same syntax i'm used to. The documentation is different from what I have provided as well.
Class 1
public class BaseTest {
public static String CBUsername = ABCD1;
public static String CBAuthkey = HIJK1;
public static String OS = "Windows 10";
public static String Build = "3";
public static String Browser = "Chrome";
public static String BrowserVersion = "73x64";
public static String Resolution = "1366x768";
public static String RecordVideo = "True";
public static String RecordNetwork = "False";
}
Class 2
#Test
public void ExampleTest throws MalformedURLException, UnirestException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("name", "Dashboard"); // Set Name To Test Name
caps.setCapability("build", Build); // Set Build To Version Of Release
caps.setCapability("browserName", Browser); //Custom
caps.setCapability("version", BrowserVersion); //Custom
caps.setCapability("platform", OS); //Custom
caps.setCapability("screenResolution", Resolution); //Custom
caps.setCapability("record_video", RecordVideo); //Custom
caps.setCapability("record_network", RecordNetwork); //Custom
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://" + CBUsername + ":" + CBAuthkey +"#hub.crossbrowsertesting.com:80/wd/hub"), caps);
try {
/* Set testScore to fail in-case an error is discovered at runtime. */
myTest.testScore = "fail";
/*
* Enter Code Here
*
*/
/* if we get to this point, then all the assertions have passed. */
myTest.testScore = "pass";
}
catch(AssertionError ae) {
String snapshotHash = myTest.takeSnapshot((driver).getSessionId().toString());
myTest.setDescription((driver).getSessionId().toString(), snapshotHash, ae.toString());
myTest.testScore = "fail";
}
finally {
System.out.println("Test complete: " + myTest.testScore);
// here we make an api call to actually send the score
myTest.setScore((driver).getSessionId().toString(), myTest.testScore);
// and quit the driver
driver.quit();
}
}
public JsonNode setScore(String seleniumTestId, String score) throws UnirestException {
/* Mark a Selenium test as Pass/Fail */
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.put("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.field("action","set_score")
.field("score", score)
.asJson();
return response.getBody();
}
String takeSnapshot(String seleniumTestId) throws UnirestException {
/*
* Takes a snapshot of the screen for the specified test.
* The output of this function can be used as a parameter for setDescription()
*/
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.post("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}/snapshots")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.asJson();
// grab out the snapshot "hash" from the response
String snapshotHash = (String) response.getBody().getObject().get("hash");
return snapshotHash;
}
public JsonNode setDescription(String seleniumTestId, String snapshotHash, String description) throws UnirestException{
/*
* sets the description for the given seleniemTestId and snapshotHash
*/
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.put("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}/snapshots/{snapshotHash}")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.routeParam("snapshotHash", snapshotHash)
.field("description", description)
.asJson();
return response.getBody();
}
}
}
Found a solution that might help others with a similar question
java.lang.NullPointerException Selenium 2 classes
public class PP_Main {
private static RemoteWebDriver driver;
private static String homeUrl;
//...
#BeforeClass
public static void setUp() throws Exception {
// ...
cap.setPlatform(Platform.ANY);
driver = new RemoteWebDriver(new
URL("http://51.19.210.111:5555/wd/hub"), cap);
// ...
}
Related
am trying to implement depends on methods
i have given depends on login as agent for booking an appointment but its showing non exist method
ihave given #data provider and depends on method
this is login test case
public class TC001_Login extends ProjectSpecificMethods{
#BeforeTest
public void setValues() {
testCaseName = "Login";
testDescription = "This test is to verify whether user able to login and logout";
nodes = "login";
authors = "manoj";
category = "Smoke";
}
#Test(priority = 0)
public void loginAsAgent() throws InterruptedException, IOException {
new LoginPage(driver, node)
.enterUserName()
.enterPassword()
.enterCaptchAndClickLogin()
.clickOnLogout()
.verifyLogout();
}
}
this is appointment booking test case
public class TC003_BookAppointment extends ProjectSpecificMethods {
#BeforeTest
public void setValues() {
testCaseName = "bookappointment";
testDescription = "booking an appointment";
nodes = "appointment,appointment1";
authors = "manoj";
category = "Smoke";
dataSheetName = "ScheduleAppointment";
sheetName = "TestData";
}
#Test(dataProvider = "fetchData",dependsOnMethods = {"loginAsAgent"})
public void bookappointment(String visatype,String VscCode,String noofapplicants,String date,String path) throws IOException, Exception {
new LoginPage(driver, node)
.enterUserName()
.enterPassword()
.enterCaptchAndClickLogin()
.clickGroupScheduling()
.selectVisaType(visatype)
.selectVscCenter(VscCode)
.selectNumberOfApplicants(noofapplicants)
.enterCaptcha()
.selectDate_Normal(date)
.selectTime()
.confirmSlot_Normal()
.submitScheduling_Normal()
.generatePassportNumber()
.uploadexcel(path)
.clickUploadexcel()
.clickConsentcheckbox()
.clickSaveApplicantDetais()
.downloadAppointmentslip()
.downloadGroupSchedulingForm()
.verifyGroupid();
}
}
tried to give classname.methodname but not working
I need to validate my ui data and api responses are same,
here is my code I tried,
private ValidateContentPage cp = new ValidateContentPage();
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
here im getting my api responses,
public class ValidateContentPage {
public common cm = new common();
public Properties prop;
public void baseURI() {
prop = cm.getProperties("./src/test/API/IndiaOne/propertyfile/EndpointURL.properties");
RestAssured.baseURI = prop.getProperty("baseURI");
}
public String getAPICall() {
objectpojo ps = given().expect().defaultParser(Parser.JSON).when().get(prop.getProperty("resources")).as(objectpojo.class, cm.getMapper());
int number = ps.getPosts().size();
System.out.println(number);
System.out.println(ps.getPosts().get(0).getTitle());
return ps.getPosts().get(0).getTitle();
}
If i validate both using testng assertion it throwing null pointer exception, anyone help me on how to validate my ui data and api responses.
You need to call your ValidateContentPage from #Test itself or from #BeforeTest
#Test
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
ValidateContentPage cp = new ValidateContentPage();
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
I am trying to send my tests to testrail from selenium but im not using an assert to end the test, i just want it to pass if it runs to completion? Is this possible? Also is there any examples of how this working in the code? I currently have:
public class login_errors extends ConditionsWebDriverFactory {
public static String TEST_RUN_ID = "R1713";
public static String TESTRAIL_USERNAME = "f2009#hotmail.com";
public static String TESTRAIL_PASSWORD = "Password100";
public static String RAILS_ENGINE_URL = "https://testdec.testrail.com/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test
public void login_errors() throws IOException, APIException {
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
login_errors.addResultForTestCase("T65013",TEST_CASE_PASSED_STATUS," ");
}
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
}
I am getting a 401 status from this code.
Simply place the addResultForTestCase method at the end of the run. Ensure the Test CASE is used rather than the run id. You are currently using the incorrect ID
I am having trouble sending my test results from selenium to testrail. I cant seem to figure it out using the paperwork provided. I am currently using this:
public class login_errors extends ConditionsWebDriverFactory {
public static String TEST_RUN_ID = "R1713";
public static String TESTRAIL_USERNAME = "testemai9#hotmail.com";
public static String TESTRAIL_PASSWORD = "Password1";
public static String RAILS_ENGINE_URL = "https://testproj.testrail.com/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test
public void login_errors() throws IOException, APIException {
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
login_errors.addResultForTestCase(TEST_RUN_ID,TEST_CASE_PASSED_STATUS," ");
}
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
}
But i keep getting the following exception:
com.gurock.testrail.APIException: TestRail API returned HTTP
401("Authentication failed: invalid or missing user/password or
session cookie.")
Can anybody help me on the exact way this should be done out in java? I am not sure I am doing it correctly.
I'm using my own custom made API for testrail, but it is all based on same thing.
But looking to official gurrock,
documentation
First You need to add "testrail/" at the end of Your URL endpoint,
APIClient client = new APIClient("http://<server>/testrail/");
client.setUser("..");
client.setPassword("..");
Should be like this:
public static String RAILS_ENGINE_URL ="https://testproj.testrail.com/testrail/";
Second thing what I found out is that You're sending test run id in variable for testcase ID, this is not same.
And another thing is that test case ID shouldn't be with anything in front just pure number, not like "R123" but "123"
And Your method should than accept one more parameter, testRunId
public static void addResultForTestCase(String testRunId, String testCaseId, int status,String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
And another thing is that You have to have created testrun, so You can have Yourself your testrun ID, like pic bellow:
And than test case ID is different from testrun id.
I have tried to write a little code using libGDX to work with network. Here's a code:
public class Test {
public static void main(String[] args) {
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
If I write this URL in browser, it works right. It means, that the problem on my side. How to fix it?
Summary of values of the object which causes NullPointerException:
You are writing this code in the static main entry point of your program. Your Gdx is not yet loaded,so Gdx is still null at this point.
Create a none static class and put your code in it's constructor and initialize that class within this static entry point.
public class WebTest()
{
public WebTest()
{
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
}
public class Test {
public static void main(String[] args) {
new WebTest();
}
}