I'm trying to check login page control by using dataprovider but i don't want to initialize webdriver again and again for each username password control. Once i come into login page, checking all concerned scenarios on login page in single time without starting another driver seems more convenient to me but i couldn't figure it out. When running following code, data[0][0] and data[0][1] is being correctly checked but it gives no such element on Login method having second priority test annotation when being tried to be typed data[1][0] and data[1][1]. Probably, it causes because driver is not looking at that page on that time. How can I handle this issue ?
error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class='q-input-wrapper email-input']//input[#class='q-input']"}
code:
public class TestCaseFirst {
public WebDriver driver;
#BeforeTest
public void Start() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver= new ChromeDriver();
driver.get("https://www.faxzas.com/");
driver.manage().window().maximize();
Thread.sleep(2000);}
#Test(priority=1)
public void RoadtoLogin() throws InterruptedException {
driver.findElement(By.xpath("//a[#title='Close']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='login-container']//span[#id='not-logged-in-container']")).click();;
Thread.sleep(1000);
}
#Test(dataProvider="loginInfos", priority=2)
public void Login(String mail, String password) throws InterruptedException {
driver.findElement(By.xpath("//div[#class='q-input-wrapper email-input']//input[#class='q-input']")).sendKeys(mail);
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='q-input-wrapper']//input[#class='q-input']")).sendKeys(password);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#type='submit']")).click();
Thread.sleep(1000);
String description = driver.findElement(By.xpath("//div[#id='error-box-wrapper']//span[#class='message']")).getText();
System.out.println(description);
}
#DataProvider(name="loginInfos")
public Object[][] getData(){
Object[][] data = new Object[6][2];
data[0][0]="blackkfredo#gmail.com";
data[0][1]="";
data[1][0]="blackkfredo#gmail.com";
data[1][1]="443242";
data[2][0]="";
data[2][1]="1a2b3c4d";
data[3][0]="";
data[3][1]="";
data[4][0]="blackkfredogmail.com";
data[4][1]="1a2b3c4d";
data[5][0]="blackkfredo#gmail.com";
data[5][1]="1a2b3c4d";
return data;
}
}
You need to reset your page to the login page where you are expecting the element to be. Either put an #AfterMethod and go back to the page you are trying to test or put an #BeforeMethod for the same. You may even want to wrap up your find element calls and handle the exceptions by going back to the main page.
I am completely stuck in a java test; it's about sending by the test method the character 'a' to the JTextField of a JFrame component.
The JFrame class implements the KeyListener interface, and as such overrides KeyPressed, KeyTyped, and KeyReleased. Along with this, I transfer all the keypressed of the JTextField to the JFrame; inside the JFrame constructor I have :
JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);
I would like to test this behavior and then to simulate the action of type a character in the JTextField.
all my attempts failed; I tried with the java.awt.Robot class, like this : hava a look at this other post in stack overflow, but I get a strange behavior : calling
robot.keyPress(KeyEvent.VK_A);
displays the character in my IDE directly, not in the virtual JFrame! try to play with requestFocus() or requestFocusInWindow() is ineffective.
I also tried with KeyEvents:
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
but again the textfield's text property is not changed...
here is the method I have for now:
#Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException {
initTest();
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());
assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
}
I can have a look at the actual behavior by writing a main() method in the JFrame's child class, but I think it is useful to know how to simulate keys for swing components testing.
thank you
EDIT:
I changed the code of my test according to AJNeufeld's answer, but it still doesn't work. Here is my test code :
#Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException,
InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
bookWindow = new BookWindow();
VectorPerso two = new VectorPerso();
two.add(le_livre_de_la_jungle);
two.add(elogeMaths);
bookWindow.setTableDatas(two);
bookWindow.table.setRowSelectionInterval(1, 1);
bookWindow.txf_version.requestFocusInWindow();
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());
assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});
}
the plintln line produces a text in the console : "dans txf_version : 0", which indicates the key isn't send to the txf_version.
EDIT 2:
new try:
#Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException,
InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
bookWindow = new BookWindow();
VectorPerso two = new VectorPerso();
two.add(le_livre_de_la_jungle);
two.add(elogeMaths);
bookWindow.setTableDatas(two);
bookWindow.table.setRowSelectionInterval(1, 1);
bookWindow.txf_version.requestFocusInWindow();
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeAndWait(() -> {
System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());
assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});
}
I think you're doing a couple of things wrong, but without a complete example, it is hard to tell.
First, the JTextField is not really concerned with KEY_PRESSED events. It is concerned with the KEY_TYPED events.
Second, Swing processes events on the Event Dispatching Thread (EDT), which is not necessarily the thread that JUnit is going to be running on. You really shouldn't be changing things when you're not on the EDT. I'm not certain eventDispatch() does the switch to the EDT or not. It might. But it might also do it using invokeLater(), in which case the execution immediately passes to the assertEquals(), which fails, because the event processing hasn't happened yet.
Here is minimal, complete, verifiable example, which shows a keypress sent, which changes the button colour, and a JUnit test case which checks it and passes:
First, the code under test:
public class SwingUnitTesting extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(SwingUnitTesting::new);
}
JTextField tf = new JTextField();
JButton btn = new JButton("Test Button");
SwingUnitTesting() {
add(tf, BorderLayout.PAGE_END);
add(btn, BorderLayout.PAGE_START);
tf.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
btn.setForeground(Color.RED);
}
});
setSize(200, 80);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
}
And the unit test:
public class SwingUnitTestingTest {
SwingUnitTesting sut;
#Before
public void setUp() throws Exception {
SwingUtilities.invokeAndWait(() -> {
sut = new SwingUnitTesting();
});
}
#Test
public void btnNotRedBeforeKeypress() throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
assertNotEquals(Color.RED, sut.btn.getForeground());
});
}
#Test
public void btnRedAfterKeypress() throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
sut.tf.requestFocusInWindow();
sut.tf.dispatchEvent(new KeyEvent(sut.tf,
KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0,
KeyEvent.VK_UNDEFINED, 'A'));
assertEquals(Color.RED, sut.btn.getForeground());
});
}
}
You can probably use some JUnit #Rule trickery or a custom runner to automatically change to the EDT when running swing tests.
Update:
I got curious, and tried to find an existing #Rule which puts the #Before, #Test, and #After code on to the EDT, but my Google-fu failed me;
I know I've seen it before, but I couldn't find it.
In the end, I created my own:
public class EDTRule implements TestRule {
#Override
public Statement apply(Statement stmt, Description dscr) {
return new Statement() {
private Throwable ex;
#Override
public void evaluate() throws Throwable {
SwingUtilities.invokeAndWait(() -> {
try {
stmt.evaluate();
} catch (Throwable t) {
ex = t;
}
});
if (ex != null) {
throw ex;
}
}
};
}
}
Using this rule, the JUnit test becomes a little simpler:
public class SwingUnitTestingTest {
#Rule
public TestRule edt = new EDTRule();
SwingUnitTesting sut;
#Before
public void setUp() throws Exception {
sut = new SwingUnitTesting();
}
#Test
public void btnNotRedBeforeKeypress() {
assertNotEquals(Color.RED, sut.btn.getForeground());
}
#Test
public void btnRedAfterKeypress() {
sut.tf.requestFocusInWindow();
sut.tf.dispatchEvent(
new KeyEvent(sut.tf, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'A'));
assertEquals(Color.RED, sut.btn.getForeground());
}
}
Tested on MacOS, with jdk1.8.0_121
Yo, I guess you have two choices
1) It's still to find a solution using SWING (but in this case, I have no experience and any idead how to help you).
2) It's to use Sikulli java framework for testing desktop app. You can add the dependency then
make screenshot of your UI elements, and put them into test data folder of your app
Using sikuli + JUnit
write simple test where you set a path for your pic of button (for example)
and write action, move, click or what actually you need.
in very simple that will be looks like
Button button = new Button("test-folder/pic1.jpg");
button.click();
After run, you will see that, your cursor was move on button, and click by it.
For more details, find examples in web about Sikulli + Java.
recently I had to test a customized KeyAdapter and I created a customized JTextField to dispatch key events. A piece of the code I used is bellow:
public class ProcessKeyOnTextFieldTest {
#Test
public void pressKeyTest() throws Exception {
JTextFieldWithTypedKeySupport textField = new JTextFieldWithTypedKeySupport();
textField.pressKey('a');
textField.pressKey('b');
assertEquals("ab", textField.getText());
}
class JTextFieldWithTypedKeySupport extends JTextField {
int timestamp;
void pressKey(char key) throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> super.processKeyEvent(createEvent(key)));
}
KeyEvent createEvent(char keyChar) {
return new KeyEvent(this, KeyEvent.KEY_TYPED, timestamp++, 0, KeyEvent.VK_UNDEFINED, keyChar);
}
}
}
package p111;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yahoo_c {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Above is the code.
When i run this, execution goes until "pizza" being entered into yahoo search.Later with no error message in console execution terminates.
The error image is
Please help resolve this issue.Am trying to select pizza delivery from list.
You can try Name instead of path as the yahoo search has a name for selenium to work with. Please let know if Xpath is must for you to work then i will change my code.
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.name("p"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Or you can use the same by ID
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.id("UHSearchBox"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
The option you are trying to click is a link in <a> anchor tag.. you can simply use By.linkText if you are specific on the link.
driver.findElement(By.linkText("pizza delivery")).click();
Problem is that you are sendKeys, even though the pizza is typed but the drop-down list does not appears because sendKeys is not equivalent of typing through keyboard. Work around is simple. You need to perform a keyboard action after writing "pizza".
// type pizza
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
// now perform keyboard action (of pressing space key)
wi.findElement(By.xpath("String")).SendKeys(Keys.Space);
// now click on the pizza delivery link
wi.findElement(By.linkText("pizza delivery")).click();
Try above code in your project, after adding proper wait and with correct element locators.
Try this xpath //*[contains(text(),'pizza delivery')]
It'll work! :)
Check this in firepath and make sure you get only one node with the locator.
I'm trying to use JACOB to obtain a callback whenever a slide show starts or ends using the following:
public class Test {
public static void main(String[] args) {
ActiveXComponent oApp = new ActiveXComponent("PowerPoint.Application");
Dispatch presentations = oApp.getProperty("Presentations").toDispatch();
Dispatch presentation = Dispatch.call(presentations, "Open", "C:\\Users\\Bob\\Documents\\test.ppt").toDispatch();
new DispatchEvents(oApp, new Handler());
}
}
public class Handler {
public void SlideShowBegin(Variant[] args) {
System.out.println("here");
}
}
However, I'm coming a bit unstuck, the result of the above is:
GetEventIID: couldn't get IProvideClassInfo
Exception in thread "main" com.jacob.com.ComFailException: Can't find event iid
at com.jacob.com.DispatchEvents.init3(Native Method)
at com.jacob.com.DispatchEvents.<init>(DispatchEvents.java:138)
at com.jacob.com.DispatchEvents.<init>(DispatchEvents.java:99)
at com.jacob.com.DispatchEvents.<init>(DispatchEvents.java:72)
at tester.Test.main(Test.java:28)
Does anyone have any ideas? Searching has come up pretty short. I've tried using the 4 argument constructor of DispatchEvents, supplying "Powerpoint.Application" and the full path to the powerpoint exe as the last two arguments, but no difference.
Does Webdriver 2.28 automatically take a screenshot on exception/fail/error?
If it does, where can I find the screenshot? Which directory is the default?
No, it doesn't do it automatically. Two options you can try:
Use WebDriverEventListener that is attachable to a EventFiringWebDriver which you can simply wrap around your usual driver. This will take a screenshot for every Exception thrown by the underlying WebDriver, but not if you fail an assertTrue() check.
EventFiringWebDriver driver = new EventFiringWebDriver(new InternetExplorerDriver());
WebDriverEventListener errorListener = new AbstractWebDriverEventListener() {
#Override
public void onException(Throwable throwable, WebDriver driver) {
takeScreenshot("some name");
}
};
driver.register(errorListener);
If you're using JUnit, use the #Rule and TestRule. This will take a screenshot if the test fails for whatever reason.
#Rule
public TestRule testWatcher = new TestWatcher() {
#Override
public void failed(Throwable t, Description test) {
takeScreenshot("some name");
}
};
The takeScreenshot() method being this in both cases:
public void takeScreenshot(String screenshotName) {
if (driver instanceof TakesScreenshot) {
File tempFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(tempFile, new File("screenshots/" + screenshotName + ".png"));
} catch (IOException e) {
// TODO handle exception
}
}
}
...where the FileUtils.copyFile() method being the one in Apache Commons IO (which is also shipped with Selenium).
WebDriver does not take screenshot itself. But you cat take by this way : ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
Then save the screenshot anywhere you want.
Also you cat use something like Thucydides, wich may take screenshot on each action or on error and put it in a pretty report.
The short answer is No. WebDriver is an API to interact with the browser. You can make screenshots with it but you should know when to do it. So it's not done automatically as WebDriver doesn't know anything about testing.
If you are using TestNG as testing library you can implement Listener whose methods will be executed on different events (failure, success or other). In these methods you can implement the required logic (e.g. making screenshots).