TestNG not running #Test for Firefox Driver -- Chrome working - selenium-chromedriver

I am building Selenium WebDriver tests for Chrome and Firefox in Eclipse using TestNG. When I run the testng.xml file as a TestNG Suite, it opens the Firefox browser, but does not enter the #Test method in the class file. It does the #BeforeClass method just fine.
However, when I have virtually the same code but for Chrome, it works fine - it enters the #Test method and everything is golden.
Any idea why it would enter the #Test method for Chrome, but not Firefox?
Here is the code for my class:
public class TestFireFox {
private WebDriver driver;
#BeforeClass
public void beforeClass() {
System.out.println("Running TestFireFox Class");
driver = new FirefoxDriver();
System.setProperty("webdriver.gecko.driver", "geckodriver");
}
#AfterClass
public void afterClass() {
driver.quit();
}
#Test
public void verifySearchButton() {
System.out.println("Inside Verify Method");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com");
String search_text = "Google Search";
WebElement search_button = driver.findElement(By.name("btnK"));
String text = search_button.getAttribute("value");
Assert.assertEquals(text, search_text, "Text not found!");
}
}

The problem might be the order of statements. You need setProperty before instatiate Firefox.
System.setProperty("webdriver.gecko.driver", "path\\to\\geckodriver.exe");
driver = new FirefoxDriver();

Related

How to load values from custom properties file for junit testing using Mockito?

I have written this test class to check a service. This is in folder test/java/example/demp/Test.java
#RunWith(MockitoJUnitRunner.class)
#TestPropertySource("classpath:conn.properties")
public class DisplayServiceTest {
#Value("${id}")
private String value;
#Mock
private DisplayRepository DisplayReps;
#InjectMocks
private DisplayService DisplayService;
#Test
public void whenFindAll_thenReturnProductList() {
Menu m = new Menu()
m.setId(value); //when I print value its showing 0
List<Display> expectedDisplay = Arrays.asList(m);
doReturn(expectedDisplay).when(DisplayReps).findAll();
List<Display> actualDisplay = DisplayService.findAll();
assertThat(actualDisplay).isEqualTo(expectedDisplay);
}
My properties file
This is in folder test/resources/conn.properties
id=2
What is the right way to set properties from custom properties file? Cause its not loading values ?
Mockito is a mocking framework, so in general you can't load properties file with Mockito.
Now you've used #TestPropertySource which is a part of Spring Testing and it indeed allows loading properties file (that have nothing to do with mockito though). However using it requires running with SpringRunner and in general its good for integration tests, not for unit tests (Spring Runner among primarily loads Spring's application context).
So if you don't want to use spring here, you should do it "manually". There are many different ways to load Properties file from class path (with getClass().getResourceAsStream() to get the input stream pointing on the resource file and the read it into Properties by using Properties#load(InputStream) for example.
You can also use other thirdparties (not mockito), like apache commons io to read the stream with IOUtils class
If you want to integrate with JUnit 4.x you can even create a rule, described here
#TestPropertySource is a spring annotation, so you need to use the SpringRunner.
You can initialize Mockito using MockitoAnnotations.initMocks(this);, check the example below.
#RunWith(SpringRunner.class)
#TestPropertySource("classpath:conn.properties")
public class DisplayServiceTest {
#Value("${id}")
private String value;
// ...
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
// ...
}
You could use just Mockito and JUnit 4. At the #Before method, call MockitoAnnotations.initMocks and load the properties file:
public class DisplayServiceTest {
private String value;
#Mock
private DisplayRepository displayReps;
#InjectMocks
private DisplayService displayService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Properties prop = loadPropertiesFromFile("conn.properties");
this.value = prop.getProperty("id");
}
private Properties loadPropertiesFromFile(String fileName) {
Properties prop = new Properties();
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream(fileName);
prop.load(stream);
stream.close();
} catch (Exception e) {
String msg = String.format("Failed to load file '%s' - %s - %s", fileName, e.getClass().getName(),
e.getMessage());
Assert.fail(msg);
}
return prop;
}
#Test
public void whenFindAll_thenReturnProductList() {
System.out.println("value: " + this.value);
Menu m = new Menu();
m.setId(this.value); // when I print value its showing 0
List<Display> expectedDisplay = Arrays.asList(m);
Mockito.doReturn(expectedDisplay).when(this.displayReps).findAll();
List<Display> actualDisplay = this.displayService.findAll();
Assert.assertEquals(expectedDisplay, actualDisplay);
}
}

Setting device name in serenity.properties file for chrome driver

How do I set the mobile emulation for Nexus 5 view in Serenity managed chrome driver?
I tried going through this link:
https://johnfergusonsmart.com/configuring-chromedriver-easily-with-serenity-bdd/
Which explain setting preferences for chrome.
Chrome preferences
You can also provide more advanced options using the setExperimentalOption() method:
Map<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downLoadDirectory);
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("pdfjs.disabled", true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
In Serenity, you would pass these using properties prefixed with the chrome_preferences prefix, e.g.
chrome_preferences.download.default_directory = /my/download/directory
chrome_preferences.profile_default_content_settings.popups = 0
chrome_preferences.pdfjs.disabled=true
From this, I tried setting the mobileEmulation as
chrome.capabilities.mobile_emulation.device_name= Google Nexus 5
chrome.options.mobileEmulation.deviceName= Google Nexus 5
and a few other logical variants, but none of them succeeded.
The best way I found to help me in this issue it to create a custom WebDriver.
I had to create a class which extends DriverSource. And then link it to the Serenity Properties file. This will give me the driver I need.
http://www.thucydides.info/docs/serenity/#_custom_webdriver_implementations
You can add your own custom WebDriver provider by implementing the
DriverSource interface. First, you need to set up the following system
properties (e.g. in your serenity.properties file):
webdriver.driver = provided
webdriver.provided.type = mydriver
webdriver.provided.mydriver = com.acme.MyPhantomJSDriver
thucydides.driver.capabilities = mydriver
Your custom driver must implement the DriverSource interface, as shown
here:
public class MyPhantomJSDriver implements DriverSource {
#Override
public WebDriver newDriver() {
try {
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
// Add
return new PhantomJSDriver(ResolvingPhantomJSDriverService.createDefaultService(),
capabilities);
}
catch (IOException e) {
throw new Error(e);
}
}
#Override
public boolean takesScreenshots() {
return true;
}
}
This driver will now take screenshots normally.

Unable to switch to WEBVIEW using Selendroid, getting WebDriverException

Im trying to automate hybrid application using Selendroid.
Im getting exception at "driver.switchTo().window("WEBVIEW").
Below is the code.
WebElement uname;
WebElement password;
#BeforeClass
public static void setUp() throws Exception{
System.out.println("Set up in progress");
SelendroidConfiguration config = new SelendroidConfiguration();
config.addSupportedApp("D:DJ/HDFC/iAgent.apk");
if(selendroidServer!=null){
selendroidServer.stopSelendroid();
}
selendroidServer = new SelendroidLauncher(config);
selendroidServer.launchSelendroid();
SelendroidCapabilities capa = new SelendroidCapabilities();
capa.setAut("com.hdfclife.msd:4.85");
capa.setEmulator(false);
//capa.setPlatformVersion(DeviceTargetPlatform.ANDROID19);
driver = new SelendroidDriver(capa);
}
#Test
public void selendroidTest() throws InterruptedException{
System.out.println("Hello.. mSD under Test -- " + driver.getCurrentUrl());
//driver.switchTo().activeElement();
driver.switchTo().window("WEBVIEW");
Thread.sleep(10000);
uname = driver.findElement(By.name("username"));
uname.sendKeys("110105");
Thread.sleep(3000);
password = driver.findElement(By.name("password"));
password.sendKeys("Hdfc#123");
Thread.sleep(3000);
WebElement loginBtn = driver.findElement(By.id("loginButton"));
loginBtn.click();
Thread.sleep(3000);
}
#AfterClass
public static void tearDown(){
selendroidServer.stopSelendroid();
driver.quit();
}
Below is the error displaying.
org.openqa.selenium.WebDriverException: CATCH_ALL: java.lang.NullPointerException
at io.selendroid.server.model.internal.WebViewHandleMapper.getWebViewByHandle(WebViewHandleMapper.java:49)
at io.selendroid.server.model.SelendroidWebDriver.init(SelendroidWebDriver.java:310)
at io.selendroid.server.model.SelendroidWebDriver.(SelendroidWebDriver.java:87)
Can any one help on this.
Thanks,
Dheeraj
Check with the WEBVIEW_01 and WEBVIEW_02 along with WEBVIEW in driver.switchto statement.
The identifier of web view can also be like above.

How to click on Switch in Android Junit Test?

I used the below code to checked and unchecked on Switch component of Android.
How to checked-unchecked on Switch by touch utility in Android Junit Testing?
// wait 2 seconds for the start of the activity
final FinalizeCalibrationActivity finalActivity = (FinalizeCalibrationActivity) monitorFinalActivity
.waitForActivityWithTimeout(2000);
assertNotNull("FinalizeCalibrationActivity is null", finalActivity);
final Switch swtSignedRdwPortal = (Switch) finalActivity
.findViewById(R.id.swt_signed_rdw_portal);
JunitUtils.waitTime(3);
swtSignedRdwPortal.setChecked(false);
JunitUtils.waitTime(3);
swtSignedRdwPortal.setChecked(true);
We cannot used Switch view directly.
It will throw failed assertions like:
"android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-views".
I've used rewrite the code like this,
// wait 2 seconds for the start of the activity
final FinalizeCalibrationActivity finalActivity = (FinalizeCalibrationActivity) monitorFinalActivity
.waitForActivityWithTimeout(2000);
assertNotNull("FinalizeCalibrationActivity is null", finalActivity);
final Switch swtSignedRdwPortal = (Switch) finalActivity
.findViewById(R.id.swt_signed_rdw_portal);
JunitUtils.waitTime(3);
finalActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
swtSignedRdwPortal.setChecked(false);
}
});
JunitUtils.waitTime(3);
finalActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
swtSignedRdwPortal.setChecked(true);
}
});
This is working fine for me in Android Junit Test.!!!

How to handle SSL errors for chrome and internet explorer in selenium Webdriver testing?

How we can handle SSL certificate errors for chrome and internet explorer with selenium web driver. When I am working with Firefox it is working fine. Could you please provide me the solution to handle SSL certificate error. Below is the code i tried.
// For Chrome
#Test
public void CRconfiguration() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\Selenium softwares\\drivers\\chromedriver.exe");
_driver = new ChromeDriver(capabilities);
System.setProperty("webdriver.chrome.driver",
"D:/Softwares/Selenium softwares/drivers/chromedriver.exe");
//_driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
login();
_driver.close();
}
//For Internet Explorer
#Test
public void IEconfiguration() throws Exception {
System.setProperty("webdriver.ie.driver",
"D:/Softwares/Selenium softwares/drivers/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setJavascriptEnabled(true);
//capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));
_driver = new InternetExplorerDriver(capabilities);
_driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
login();
_driver.close();
}
For Chrome
System.setProperty("webdriver.chrome.driver","D:\\Selenium\\chromedriver.exe");
WebDriver driver1 = new ChromeDriver();
driver1.get("https://www.flipkart.com/co");
driver1.navigate().to("javascript:document.getElementById('overridelink').click()");
For IE:
System.setProperty("webdriver.ie.driver", "D:\\Selenium\\IEDriverServer.exe");
WebDriver driver2 = new InternetExplorerDriver();
driver2.get("https://www.flipkart.com");
driver2.navigate().to("javascript:document.getElementById('overridelink').click()");
WebDriver driver = new 'your Driver'();
driver.get("your app URL");
driver.navigate().to("javascript:document.getElementById('overridelink').click()");