Académique Documents
Professionnel Documents
Culture Documents
1. Le débogage est l'activité de développement qui consiste à trouver, analyser et corriger les défauts.
2. Le débogage est l'activité de développement qui consiste à vérifier qu'un défaut a bien été corrigé, c'est-à-
dire qu'il ne provoque plus de défaillances.
3. Le débogage est l'activité de test qui consiste à rechercher les défaillances et à les compiler dans un outil
de test dédié.
4. Le débogage est l'activité de test qui consiste à trier les anomalies des faux positifs.
2 - LORS DE LA PHASE DE CONCEPTION DES SPÉCIFICATIONS, QUELLE PRATIQUE EST LA PLUS ADÉQUATE ?
3 - UN TEST AUTOMATISÉ EST EN ERREUR, POURTANT L’APPLICATION FONCTIONNE CORRECTEMENT. COMMENT CELA
S’APPELLE-T-IL ?
https://hightest.nc/ressources/test-istqb.php 1/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest
5 - LORS DE L’EXÉCUTION D’UNE CAMPAGNE DE TEST, LES CAS DE TEST FOURNISSENT UNE LIGNE DIRECTRICE QU'IL FAUT
SUIVRE À LA LETTRE.
1. Vrai. Les cas de test ont été créé de manière à assurer la meilleure couverture des tests possible, il est
essentiel de les suivre attentivement.
2. Faux. S'éloigner des cas de tests permet de couvrir des cas non prévus et ainsi d'améliorer la couverture
des tests.
3. Vrai. Les cas de test couvrent les fonctionnalités indiquées dans la spécification ; il n'est pas nécessaire de
rechercher des anomalies en-dehors de ce périmètre.
4. Faux. Les cas de test sont utilisés non pas lors des campagnes de test, mais lors des tests de
confirmation.
1. Un comportement similaire pouvant être observés au sein de deux versions différentes d’un même
applicatif.
2. Une plage de données qui, lorsqu’elles sont utilisées dans un même test, doivent générer le même
comportement.
Temps restant : 25 min 56 sec Version anglaise
3. La somme de tous les comportements possibles permettant d’effectuer une même action au sein d’un
https://hightest.nc/ressources/test-istqb.php 2/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest
applicatif donné.
4. Un recueil de règles de nommages applicable au développement d’un applicatif donné.
8 - UNE BORNE D’ACHAT DE TICKETS DE BUS INTERDIT LE PAIEMENT EN ESPÈCE, SAUF SI L’UTILISATEUR LUI PRÉSENTE
UNE CARTE D’ABONNÉ ACTIVÉE ET NON PÉRIMÉE. QUEL OUTIL EST TOUT INDIQUÉ POUR ANALYSER LES DIFFÉRENTS
COMPORTEMENTS POSSIBLES DE L’APPLICATION ?
1. I et II
2. I et III
3. II et IV
4. III et IV
https://hightest.nc/ressources/test-istqb.php 3/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest
1. Risque de voir les développeurs perdre le sens de leur responsabilité vis-à-vis de la qualité
2. Risque pour l’équipe de test de ne pas être au courant de certains changements
3. Risque pour l’équipe de test de manquer de légitimité auprès du client
4. Risque de créer un goulet d’étranglement au niveau de l’équipe de test
11 - TOUT PROJET DE TEST EST SOUMIS À DEUX GRANDES FAMILLES DE RISQUES. LESQUELS ?
12 - PARMI LES ACTIVITÉS SUIVANTES, LESQUELLES PEUVENT ÊTRE RÉALISÉES DE MANIÈRE INFORMELLE ?
https://hightest.nc/ressources/test-istqb.php 4/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest
1. le taux de conformité aux standards en vigueur de la réalisation spécifique d'un composant, système ou
processus
2. la mesure relative à la satisfaction exprimée par les clients ou utilisateurs à l'issue de la conception d'un
composant, système ou processus
3. le ratio entre la part des composants, systèmes ou processus exempt d'anomalies et la totalités de ces
objets
4. le degré par lequel un composant, système ou processus atteint des exigences spécifiées et/ou des
besoins ou attentes des clients ou utilisateurs
1. Un développeur introduit une anomalie dans son code. Cette anomalie est susceptible de générer une
erreur du système.
2. Un développeur introduit un défaut dans son code. Ce défaut est susceptible de générer une anomalie du
système.
3. Un développeur introduit un bug dans son code. Ce bug est susceptible de générer une défaillance du
système.
4. Un développeur introduit une erreur dans son code. Cette erreur est susceptible de générer un bug du
système.
17 - LES RAPPORTS D'INCIDENTS PEUVENT AVOIR PLUSIEURS OBJECTIFS. LEQUEL N'EN FAIT PAS PARTIE ?
1. Fournir aux développeurs et aux autres parties un retour sur le problème concerné pour en permettre
l'identification, la localisation et la correction nécessaires
2. Fournir aux responsables du test le moyen de suivre la qualité d'un système sous test et l'avancement du
test
3. Fournir aux chefs de projet des métriques de performance relatives à chaque développeur
4. Fournir des idées
Temps restant : 25pour l'amélioration
min 56 sec du processus de test Version anglaise
https://hightest.nc/ressources/test-istqb.php 5/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest
1. Non. L'agilité s'oppose au test manuel mais met l'accent sur les tests automatisés.
2. Non. L'agilité favorise une exécution fréquente des tests afin d'éviter les régressions d'une itération à l'autre.
3. Non. Une démarche agile se doit de rechercher constamment à améliorer les processus de
développement, donc de tester différentes solutions.
4. Non. C'est l'inverse : ce sont les standards du test qui s'opposent à l'agilité, qui délaisse la qualité au profit
de la rapidité.
1. Dès que le code est suffisamment stable. Le risque, en commençant les tests trop tôt, est de confondre ce
qui est en cours et ce qui contient réellement des défauts.
2. Dès qu'il existe un brouillon de spécification. Des bugs peuvent déjà exister dans la documentation.
3. Dès le début du développement. C'est ce qu'on appelle le TDD (test driven development).
4. Dès qu'une version alpha du projet est disponible. Il ne faut pas attendre la version bêta, car elle est
directement déployée chez le client.
TERMINÉ !
https://hightest.nc/ressources/test-istqb.php 6/6
Résultats du test en ligne - Hightest
Vous avez bien répondu à 0 question(s) sur 20, soit 0 % de réussite. Il faudrait monter
jusqu'à 65 %. Courage !
Solution
Solution
Il est possible de détecter les anomalies d’une application dès la phase de spécification,
alors que rien n’a encore été implémenté. Corriger les contradictions ou les zones
d’ombre d’une spécification, c’est déjà se prémunir contre des bugs. Voir chapitre 1.4.2,
paragraphe 'Analyse de test'.
Solution
Un test non-fonctionnel valide les aspects du logiciel qui ne sont pas liés à ses
fonctionnalités ; on teste par exemple ses performances, sa réaction aux montées en
charge, au stress… Un faux négatif correspond à un test automatisé qui ne remonte
pas d’erreur alors que le scénario testé génère une anomalie. Voir chapitre 1.2.3,
dernier paragraphe.
Solution
Si le logiciel n’est pas exécuté, nous avons affaire à un test statique. Le test fonctionnel
automatisé simule un comportement utilisateur et effectue des vérifications qui touchent
aux fonctionnalités. L'utilisabilité et les performances donnent au contraire lieu à des
tests non-fonctionnels. Pour la différence entre tests statiques et dynamiques, voir
chapitre 3.1.3.
Lors de l’exécution d’une campagne de test, les cas de test fournissent une ligne
directrice qu'il faut suivre à la lettre.
1. Vrai. Les cas de test ont été créé de manière à assurer la meilleure couverture des
tests possible, il est essentiel de les suivre attentivement.
2. Faux. S'éloigner des cas de tests permet de couvrir des cas non prévus et ainsi
d'améliorer la couverture des tests.
3. Vrai. Les cas de test couvrent les fonctionnalités indiquées dans la spécification ; il
n'est pas nécessaire de rechercher des anomalies en-dehors de ce périmètre.
4. Faux. Les cas de test sont utilisés non pas lors des campagnes de test, mais lors des
tests de confirmation.
Solution
Solution
Pour calculer le risque, il faut multiplier l’indice d’une échelle de gravité par l’indice de
l’échelle de probabilité. Voir 5.5.
Solution
Les partitions d’équivalence sont utiles pour couvrir l’ensemble des catégories d’entrées
d’un logiciel ou d’un système. Par exemple, si un film est interdit aux moins de 12 ans,
on peut distinguer deux partitions d’équivalences (âge >= 12 et âge < 12). Les tarifs
d’entrée dans les établissements culturels donnent souvent lieu à de multiples partitions
d’équivalence. Voir chapitre 4.2.1.
Solution
1. I et II
2. I et III
3. II et IV
4. III et IV
Solution
Solution
Tout projet de test est soumis à deux grandes familles de risques. Lesquels ?
Solution
Les risques liés au projet regroupent des problèmes organisationnels et des problèmes
techniques pouvant impacter négativement le déroulement du projet. Les risques liés au
produit regroupent les défaillances potentielles de l’applicatif à tester. Les tests logiciels
sont destinés à réduire les risques produit. Identifier les risques en amont permet
d’élaborer la stratégie de test la mieux adaptée. Voir 5.5.2.
Solution
Solution
Solution
Solution
La notion de qualité est propre à chaque projet et dépend des besoins des clients et
des utilisateurs finaux. Voir le glossaire du syllabus.
1. Un développeur introduit une anomalie dans son code. Cette anomalie est
susceptible de générer une erreur du système.
2. Un développeur introduit un défaut dans son code. Ce défaut est susceptible de
générer une anomalie du système.
3. Un développeur introduit un bug dans son code. Ce bug est susceptible de
générer une défaillance du système.
4. Un développeur introduit une erreur dans son code. Cette erreur est susceptible de
générer un bug du système.
Solution
L'erreur (ou méprise) est la cause de l'introduction d'un défaut, ou bug, ou anomalie,
dans le système. Cette cause peut être une mauvaise compréhension, un moment
d'inattention... Le défaut est ensuite susceptible de générer des défaillances du
système. Voir 1.2.3.
Les rapports d'incidents peuvent avoir plusieurs objectifs. Lequel n'en fait pas
partie ?
1. Fournir aux développeurs et aux autres parties un retour sur le problème concerné
pour en permettre l'identification, la localisation et la correction nécessaires
2. Fournir aux responsables du test le moyen de suivre la qualité d'un système sous
test et l'avancement du test
3. Fournir aux chefs de projet des métriques de performance relatives à chaque
développeur
4. Fournir des idées pour l'amélioration du processus de test
Solution
Solution
Voir 2.2.
1. Non. L'agilité s'oppose au test manuel mais met l'accent sur les tests automatisés.
2. Non. L'agilité favorise une exécution fréquente des tests afin d'éviter les
régressions d'une itération à l'autre.
3. Non. Une démarche agile se doit de rechercher constamment à améliorer les
processus de développement, donc de tester différentes solutions.
4. Non. C'est l'inverse : ce sont les standards du test qui s'opposent à l'agilité, qui
délaisse la qualité au profit de la rapidité.
Solution
A chaque itération, il est essentiel de s'assurer de la qualité du produit afin d'éviter les
régressions. L'agilité ne s'oppose aucunement au test ! Voir les multiples mentions du
test agile dans le syllabus de niveau Fondation.
1. Dès que le code est suffisamment stable. Le risque, en commençant les tests trop
tôt, est de confondre ce qui est en cours et ce qui contient réellement des défauts.
2. Dès qu'il existe un brouillon de spécification. Des bugs peuvent déjà exister
dans la documentation.
3. Dès le début du développement. C'est ce qu'on appelle le TDD (test driven
development).
4. Dès qu'une version alpha du projet est disponible. Il ne faut pas attendre la version
bêta, car elle est directement déployée chez le client.
Solution
2 - UN APPLICATIF EST TESTÉ AVEC SUCCÈS EN ENVIRONNEMENT DE RECETTE. IL EST MIS EN PRODUCTION. LÀ,
ON S’APERÇOIT QUE CET APPLICATIF PRODUIT DES EFFETS DE BORDS SUR UN DES AUTRES APPLICATIFS DÉJÀ EN
PRODUCTION, ET QUI EST INSTALLÉ SUR LE MÊME SERVEUR QUE LUI. QUEL ASPECT DE LA QUALITÉ AURAIT DÛ
FAIRE L’OBJET DE DAVANTAGE DE TESTS ?
1. Portabilité
2. Fonctionnalité
3. Fiabilité
4. Compatibilité
1. BDD
2. TDD
3. ATDD
4. Scrum
7 - LEQUEL DES OBJECTIFS SUIVANTS N’EST TYPIQUEMENT PAS POURSUIVI PAR LES TESTS D’ACCEPTATION ?
8 - EVE LA DEV TÉLÉPHONE À MARIELLE L’ARCHITECTE FONCTIONNELLE POUR LUI POSER UNE QUESTION. CELLE-
CI LUI DIT « LES ARCHIVES DEVRONT ÊTRE SUPPRIMÉES AUTOMATIQUEMENT AU-DELÀ D’UNE CERTAINE DURÉE.
PAR EXEMPLE, CETTE ANNÉE, IL FAUDRA SUPPRIMER LES ARCHIVES DE 1967 ET EN-DEÇÀ. CETTE SUPPRESSION
DEVRA SE FAIRE VIA UNE MOULINETTE QUI DEVRA TOURNER TOUS LES 15 DU MOIS. » EVE N’ENTEND PAS BIEN ET
COMPREND « 1976 ». ELLE IMPLÉMENTE DONC UNE FONCTION EN CE SENS. LE LOGICIEL EST MIS EN PRODUCTION
LE 30 AVRIL, ET LE 15 MAI DES ARCHIVES TROP RÉCENTES SE RETROUVENT PURGÉES. QUELLE EST LA
PROPOSITION CORRECTE ?
1. L’ensemble de documents à partir desquels les exigences d’un composant ou d’un système peuvent
être déduites
2. Une base de données dédiée aux tests et que l’on trouve typiquement en environnement de recette
3. Un outil de test permettant de générer des jeux de données
4. Un ensemble de tests de composants, constituant le niveau inférieur de la pyramide des tests
11 - LEQUEL DES FACTEURS DE SUCCÈS SUIVANTS N’EST PAS COMMUN À TOUTES LES PRATIQUES DE REVUE ?
4. La revue est menée dans une atmosphère de confiance ; les résultats ne sont pas utilisés pour
évaluer les participants
12 - LEQUEL DES PROBLÈMES SUIVANTS NE PEUT PAS ÊTRE DÉTECTÉ LORS D’UNE REVUE STATIQUE ?
13 - UNE SÉANCE DE CINÉMA EST INTERDITE AUX MOINS DE DOUZE ANS, VENDUE À MOITIÉ PRIX AUX MOINS DE
16 ANS, VENDUE AVEC 25 % DE RÉDUCTION AUX 18-25 ANS ET LES SENIORS (65 ANS ET PLUS), ET GRATUITE
POUR LES PERSONNES DONT C’EST L’ANNIVERSAIRE OU QUI SONT DÉGUISÉES. QUELLE TECHNIQUE DE TEST BOÎTE
NOIRE SERAIT LA PLUS APPROPRIÉE POUR TESTER LA BORNE DE GUICHET ?
14 - 1) COMBIEN DE TESTS SONT NÉCESSAIRES POUR OBTENIR UNE COUVERTURE DES TESTS D’INSTRUCTIONS
DE 100 % POUR LA FONCTION FOO ?
PUBLIC VOID FOO(BOOLEAN A, BOOLEAN B, BOOLEAN C){
IF ( (A || B) && C ) {
/* INSTRUCTIONS */
} ELSE {
/* INSTRUCTIONS */
}
}
1. 1
2. 2
Temps restant : 29 min 49 sec Version anglaise
https://hightest.nc/ressources/test-istqb-2.php 4/6
05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest
3. 3
4. 4
15 - LAQUELLE DES TECHNIQUES SUIVANTES N’EST PAS UNE TECHNIQUE DE TEST BASÉE SUR L’EXPÉRIENCE ?
17 - EMERIC LE SUPPORT TECHNIQUE DÉCOUVRE EN PRODUCTION QUE LES UTILISATEURS D’IPHONE NE PEUVENT
PAS INSTALLER L’APPLICATION QUI VIENT D’ÊTRE MISE EN PRODUCTION ! PARMI LES CONSEILS SUIVANTS QUE
VOUS POURRIEZ DONNER À L’ÉQUIPE À L’ORIGINE DE L’APPLICATION, LEQUEL SERAIT LE MOINS APPROPRIÉ ?
1. Les tests automatisés, pour fournir de la valeur ajoutée, doivent réaliser chaque cas de test en entier
Temps
2. Les restant :
outils 29 min 49 sec
d’automatisation des tests génèrent des informations pour chaque Version anglaise
exécution des tests
https://hightest.nc/ressources/test-istqb-2.php 5/6
05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest
(statuts, logs…)
3. Certains outils d’automatisation permettent d’enregistrer des tests, auquel cas on les mentionne
comme des outils de capture/rejeu
4. Certains outils d’automatisation des tests utilisent des fichiers de données qui contiennent, outre les
données de test et les résultats attendus, des mots clé liés à l'application à tester
1. Un identifiant
2. Un titre qui résume brièvement et précisément le problème
3. Une description du défaut pour permettre la reproduction et la résolution, y compris des logs, des
captures de base de données, des captures d'écran ou des enregistrements (si trouvés pendant
l'exécution des tests)
4. L’auteur présumé du défaut
20 - LA TRAÇABILITÉ DES TESTS EST UTILE À PLUSIEURS ACTIVITÉS. LAQUELLE N’EN FAIT PAS TYPIQUEMENT
PARTIE ?
1. Analyser l’impact sur le patrimoine de test d’un changement effectué dans les bases de tests
2. Faciliter la compréhension des cas de tests par des testeurs néophytes
3. Mesurer la couverture des exigences par les tests
4. Prioriser la correction des défauts trouvés pendant les tests
TERMINÉ !
Lequel des 4 éléments suivants ne fait pas partie des 7 principes généraux du
test logiciel ?
Solution
1. Portabilité
2. Fonctionnalité
3. Fiabilité
4. Compatibilité
Solution
Solution
Voir 2.2.
1. BDD
2. TDD
3. ATDD
4. Scrum
Solution
Voir 2.2.1.
Voir 2.1.1.
Solution
Voir 2.2.1.
Lequel des objectifs suivants n’est typiquement pas poursuivi par les tests
d’acceptation ?
Solution
Voir 2.2.4.
Solution
Voir 1.2.3.
Solution
Solution
Voir 3.1.1.
Lequel des facteurs de succès suivants n’est pas commun à toutes les pratiques
de revue ?
Solution
Voir 3.2.3.
Lequel des problèmes suivants ne peut pas être détecté lors d’une revue statique
?
Solution
Une séance de cinéma est interdite aux moins de douze ans, vendue à moitié prix
aux moins de 16 ans, vendue avec 25 % de réduction aux 18-25 ans et les seniors
(65 ans et plus), et gratuite pour les personnes dont c’est l’anniversaire ou qui
sont déguisées. Quelle technique de test boîte noire serait la plus appropriée
pour tester la borne de guichet ?
Solution
Voir 4.2.3
1) Combien de tests sont nécessaires pour obtenir une couverture des tests
d’instructions de 100 % pour la fonction foo ?
public void foo(boolean A, boolean B, boolean C){
if ( (A || B) && C ) {
/* instructions */
} else {
/* instructions */
}
}
1. 1
2. 2
3. 3
4. 4
Solution
Voir 4.3.1.
Laquelle des techniques suivantes n’est pas une technique de test basée sur
l’expérience ?
Solution
Voir 4.4.
Solution
Voir 5.2.1.
Vous avez trouvé la bonne réponse !
Solution
Voir 2.3.5.
Solution
1. Un identifiant
2. Un titre qui résume brièvement et précisément le problème
3. Une description du défaut pour permettre la reproduction et la résolution, y compris
des logs, des captures de base de données, des captures d'écran ou des
enregistrements (si trouvés pendant l'exécution des tests)
4. L’auteur présumé du défaut
Solution
Voir 5.6.
La traçabilité des tests est utile à plusieurs activités. Laquelle n’en fait pas
typiquement partie ?
1. Analyser l’impact sur le patrimoine de test d’un changement effectué dans les bases
de tests
2. Faciliter la compréhension des cas de tests par des testeurs néophytes
3. Mesurer la couverture des exigences par les tests
4. Prioriser la correction des défauts trouvés pendant les tests
Solution
Voir 1.4.4.
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest
1. Une condition ou une capacité requise par un utilisateur pour résoudre un problème ou atteindre un
objectif
2. Une condition ou capacité qui doit être tenue ou possédée par un système ou un composante pour
satisfaire un contrat, un standard, une spécification ou tout autre document imposé formellement
3. Une représentation documentée d’une condition ou d’une capacité requise
4. Selon le contexte, l’une des trois propositions ci-dessus
1. Les contre-exigences, à savoir les caractéristiques que la solution ne devra obligatoirement pas
présenter
2. Les exigences qui se positionnent comme des seuils ou attributs de base
3. Les attributs de performance, qui améliorent la satisfaction du client
4. Les attributs d’excitation, non prévus par le client, qui répondent à des « besoins inconnus » et
peuvent fournir un avantage concurrentiel significatif
1. La vérification permet de savoir si on a créé correctement le produit ; la validation permet de savoir
si le produit répond au besoin du client
2. La validation correspond à la somme de toutes les vérifications incrémentales
3. La validation est une vérification en environnement cible
4. La vérification est menée par l'équipe projet, alors que la validation est menée par des équipes
tierces (par exemple lors d'un audit)
6 - IL EXISTE TROIS GRANDS TYPES DE PROTOTYPES. LEQUEL N’EN FAIT PAS PARTIE ?
1. Le prototype vertical, qui propose un nombre réduit de fonctions, mais où chaque fonction présente
est détaillée
2. Le prototype horizontal, qui contient un grand nombre de fonctions, mais où chaque fonction est
largement incomplète
3. Le prototype diagonal, qui permet de montrer superficiellement un nombre important de
fonctionnalités, et de montrer en profondeur un petit nombre de fonctionnalités
4. Le prototype de scénario, où toutes les fonctions sont simulées pour une tâche spécifique,
combinant des prototypes verticaux et horizontaux
9 - EN ENVIRONNEMENT AGILE, PAR L’INTERMÉDIAIRE DE QUEL MÉCANISME LES EXIGENCES NE SONT PAS
COMMUNIQUÉES ?
1. Il est courant d'y représenter les acteurs humains, par exemple en les modélisant par un petit
bonhomme.
2. Dans ce type de diagramme, les cas d’utilisation représentés ne s’enchaînent pas (il n’y a pas de
représentation temporelle)
3. Il est possible d’utiliser un diagramme de cas d’utilisation pour représenter de manière
macroscopique les droits accordés à chaque grand type d’utilisateurs d’une solution
4. Les pré-requis d’un cas d’utilisation sont exprimés par le mot-clé « extend »
1. Les diagrammes d’activité mettent l’accent sur les traitements en se focalisant sur les actions, en
opposition avec les objets.
2. Un diagramme d’activité peut être réalisé pour décrire un cas d’utilisation.
3. Dans la représentation d’une transition conditionnelle, les différentes décisions doivent être
mutuellement exclusives.
4. Les actions sont représentées par des arcs et les transitions sont représentées par des noeuds.
12 - QUELLE PHRASE SUR LES DIAGRAMMES D’ÉTAT-TRANSITION (OU DIAGRAMMES DE MACHINE À ÉTATS, OU
STATECHARTS) EST FAUSSE ?
1. Ce diagramme offre une vision complète et non-ambiguë de l’ensemble des comportements de
l’élément représenté.
2. Ce diagramme représente un élément du système au sein de son environnement : les acteurs
(humains ou systèmes) y figurent.
3. Les temps d’attente peuvent figurer sur ce type de diagramme.
4. Il est obligatoire de représenter l’état initial, mais pas le ou les états finaux.
15 - SELON IREB, LES MODÈLES ONT TROIS CARACTÉRISTIQUES ESSENTIELLES. LAQUELLE N’EN FAIT PAS PARTIE
?
16 - LEQUEL DE CES ASPECTS NE FAIT PAS PARTIE DES HUIT CRITÈRES DE VALIDATION DU CONTENU D’UNE
EXIGENCE ?
17 - LAQUELLE DE CES ACTIVITÉS NE FAIT PAS PARTIE DES 4 ACTIVITÉS DE LA NÉGOCIATION DES EXIGENCES ?
1. Analyse du conflit
2. Elaboration de scénarios de résolution
3. Résolution du conflit
4. Documentation de la résolution du conflit
20 - SELON IREB, IL EXISTE TROIS SORTES DE CHANGEMENTS DANS LES EXIGENCES. LEQUEL N’EN FAIT PAS
PARTIE ?
TERMINÉ !
1. Une condition ou une capacité requise par un utilisateur pour résoudre un problème
ou atteindre un objectif
2. Une condition ou capacité qui doit être tenue ou possédée par un système ou un
composante pour satisfaire un contrat, un standard, une spécification ou tout autre
document imposé formellement
3. Une représentation documentée d’une condition ou d’une capacité requise
4. Selon le contexte, l’une des trois propositions ci-dessus
Solution
La définition de IEEE 610 de 1990, reprise par le lexique IREB, donne cette triple
définition de l'exigence.
Solution
Une manière d'exprimer la portée contractuelle est d'utiliser les verbes 'devoir' (à
l'indicatif ou au conditionnel) et 'pouvoir', ce qui correspond à la notation MoSCoW
(Must, Should, Could, Won't). IREB recommande d'exprimer la portée contractuelle via
des attributs d'exigences (UE 5.2 du syllabus IREB de niveau Fondamentaux).
Solution
Le modèle de Kano est cité dans l'UE 3.2 du syllabus IREB de niveau Fondamentaux.
Ce modèle permet de penser les attendus et les centres de satisfaction des utilisateurs
finaux, des aspects décisifs pour la gestion des exigences.
Solution
La vérification concerne l'adéquation entre le résultat final et l'objectif qui a été fixé. La
validation permet de confirmer que l'objectif fixé est bien le bon et répond au besoin réel
d'un contexte donné. Ces notions définies notamment dans ISO 9000:2015.
Solution
Il existe trois grands types de prototypes. Lequel n’en fait pas partie ?
Solution
Solution
Cet aspect est évoqué dès l'UE 1 du syllabus IREB de niveau Fondamentaux.
Solution
Les critères d'acceptation d'une exigence sont évoqués dans l'UE 4.3 du syllabus IREB
de niveau Fondamentaux. Ils sont précieux en ce qu'ils permettent à toutes les parties
prenantes de déterminer si telle exigence a été remplie.
1. Le product backlog
2. Les user stories
3. Les daily scrums
4. Les mockups
Solution
L'agilité n'est pas évoquée dans le syllabus IREB de niveau Fondamentaux, mais il est
intéressant de pouvoir faire le lien entre les pratiques agiles et l'ingénierie des
exigences. L'agilité est étudiée dans le syllabus REQB niveau Fondation.
1. Il est courant d'y représenter les acteurs humains, par exemple en les modélisant par
un petit bonhomme.
2. Dans ce type de diagramme, les cas d’utilisation représentés ne s’enchaînent pas (il
n’y a pas de représentation temporelle)
3. Il est possible d’utiliser un diagramme de cas d’utilisation pour représenter de
manière macroscopique les droits accordés à chaque grand type d’utilisateurs d’une
solution
4. Les pré-requis d’un cas d’utilisation sont exprimés par le mot-clé « extend »
Solution
Dans un diagramme de cas d'utilisation UML, les pré-requis d'un cas d'utilisation sont
exprimés par le mot-clé « include ».
1. Les diagrammes d’activité mettent l’accent sur les traitements en se focalisant sur les
actions, en opposition avec les objets.
2. Un diagramme d’activité peut être réalisé pour décrire un cas d’utilisation.
3. Dans la représentation d’une transition conditionnelle, les différentes décisions
doivent être mutuellement exclusives.
4. Les actions sont représentées par des arcs et les transitions sont représentées
par des noeuds.
Solution
Dans un diagramme d'activité UML, les actions sont représentées par des noeuds et les
transitions par des arcs.
Solution
1. Le périmètre du système
2. Les limites du contexte
3. Les exigences fonctionnelles
4. Les processus métier
Solution
Solution
Ces notions sont expliquées dans l'UE 3.1 du syllabus IREB de niveau Fondamentaux.
Selon IREB, les modèles ont trois caractéristiques essentielles. Laquelle n’en fait
pas partie ?
Solution
Les trois caractéristiques essentielles des modèles sont indiquées dans l'UE 6.1 du
syllabus IREB de niveau Fondamentaux.
Vous avez trouvé la bonne réponse !
Lequel de ces aspects ne fait pas partie des huit critères de validation du contenu
d’une exigence ?
Solution
L'entente après changement fait partie des trois critères de validation de la facette
'accord' d'une exigence. Les facettes de la qualité des exigences (contenu,
documentation et accord) sont expliquées dans l'UE 7.3 du syllabus IREB de niveau
Fondamentaux.
Laquelle de ces activités ne fait pas partie des 4 activités de la négociation des
exigences ?
1. Analyse du conflit
2. Elaboration de scénarios de résolution
3. Résolution du conflit
4. Documentation de la résolution du conflit
Solution
Les quatre activités de la négociation des exigences (UE 7.6) sont l'identification du
conflit, l'analyse du conflit, la résolution du conflit et la documentation de la résolution du
conflit.
Solution
Ces quatre activités sont indiquées dans l'UE 1 du syllabus IREB de niveau
Fondamentaux.
Solution
Cette matrice est évoquée dans l'UE 8.3 du syllabus IREB de niveau Fondamentaux.
Pour plus de détails, consultez l'article de Karl Wiegers.
Solution
Les trois sortes de changements sont listées dans l'UE 8.6 du syllabus IREB de niveau
Fondamentaux.
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
1. Le fait de pousser plus de tests plus tôt dans le cycle de vie du développement logiciel pour trouver
et supprimer les défauts du code plus tôt.
2. Une méthode générale pour rendre libre une oeuvre (notamment un programme informatique) et
obliger toutes les versions modifiées ou étendues de ce programme à être libres également
3. Une méthode de gestion de la production (notamment informatique) qui se concentre sur la
réduction des efforts inutiles (ou 'gaspillage').
4. Une méthode de test continu du logiciel quand celui-ci se trouve dans un environnement de
production.
2 - LES TESTEURS HUMAINS POSSÈDENT PLUSIEURS ATOUTS DONT LES TESTS AUTOMATISÉS SONT DÉNUÉS.
LEQUEL DE CES ATOUTS N'EST PAS PROPRE AUX HUMAINS ?
3 - LEQUEL DES ÉLÉMENTS SUIVANTS NE FAIT PAS PARTIE DES FACTEURS DE SUCCÈS DE L'AUTOMATISATION DES
TESTS ?
1. Les organisations sont souvent tellement préoccupées par les tests via l'interface graphique qu'elles
peuvent oublier que la pyramide des tests suggère que davantage de tests unitaires/composants soient
effectués.
2. Les tests fonctionnels dynamiques automatisés mettent généralement en oeuvre des scénarios
plus éloignés des comportements utilisateurs que ceux des tests unitaires.
3. Lors du test d'un workflow dans un contexte d’intégration continue, les tests fonctionnels
dynamiques automatisés peuvent rendre le build beaucoup plus long que prévu.
4. Les modifications apportées à l’interface utilisateur ont un impact sur les tests au niveau du
navigateur plus important que les tests au niveau unitaire ou de l'API.
5 - L'ARCHITECTURE D'AUTOMATISATION DES TESTS (AAT) SE COMPOSE DE 4 COUCHES. LAQUELLE N'EN FAIT PAS
PARTIE ?
1. Couche d'adaptation des tests : fournit les objets et le code nécessaires à l'interface avec le SUT
(système testé) à différents niveaux
2. Couche de correspondance des tests : prend en charge la traçabilité entre les cas de test manuels et
les scripts de tests automatisés.
3. Couche de définition des tests : prend en charge la définition et l'implémentation des cas de test
et/ou des suites de tests.
4. Couche d'exécution des tests : supporte à la fois l'exécution des tests automatisés et
l'enregistrement des résultats.
6 - PLUSIEURS MÉTRIQUES SONT PROPOSÉES POUR UN PETIT PROJET D'AUTOMATISATION DES TESTS. LAQUELLE
N'EN FAIT PAS PARTIE ?
Temps restant : 29 min 53 sec Version anglaise
https://hightest.nc/ressources/test-a4q-selenium.php 2/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
1. Taux de couverture des tests unitaires portant sur les classes utilisées par les tests Selenium
2. Effort de test de régression qui a été économisé par l'automatisation.
3. Effort déployé par l'équipe d'automatisation en support à l'automatisation.
4. Couverture des User Stories (en projet agile)
8 - QUEL EST LE LANGAGE QUI DÉFINIT SÉMANTIQUEMENT LA STRUCTURE D'UNE PAGE WEB ?
1. XML
2. CSS
3. HTML
4. JavaScript
9 - UNE APPLICATION WEB DE JEU EN LIGNE AFFICHE SUR UNE PAGE LE CLASSEMENT DES JOUEURS. QUELLE
BALISE EST LA PLUS APPROPRIÉE POUR CONTENIR LA LISTE DE CES JOUEURS ?
1. <ol>[...]</ol>
2. <ul>[...]</ul>
3. <li>[...]</li>
4. <br>[...]</br>
10 - UN TABLEAU PRÉSENT SUR UNE PAGE WEB CONTIENT DES INFORMATIONS SUR LES UTILISATEURS D'UNE
L'APPLICATION. DANS LA COLONNE 1 SE TROUVE L'IDENTIFIANT DE L'UTILISATEUR, DANS LA COLONNE 2 SON
NOM, DANS LA COLONNE 3 SON PRÉNOM, ET DANS LA COLONNE 4 SON ADRESSE E-MAIL. QUEL EST L'XPATH
Temps restant : 29 min 53 sec Version anglaise
PERMETTANT DE RÉCUPÉRER L'ADRESSE E-MAIL DE L'UTILISATEUR DONT L'IDENTIFIANT EST NICOLAS ?
https://hightest.nc/ressources/test-a4q-selenium.php 3/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
1. //tr[contains(., 'Nicolas')]/following-sibling::td[3]
2. //td[contains(., 'Nicolas')]/following-sibling::td[3]
3. //td[contains(., 'Nicolas')]/following-sibling::td[2]
4. //tr[contains(., 'Nicolas')]/following-sibling::td[2]
11 - ETANT DONNÉ LE CODE SUIVANT (CORRESPONDANT AU PETIT FORMULAIRE AFFICHÉ POUR INFORMATION),
PLUSIEURS SÉLECTEURS CSS PERMETTENT D'INTERAGIR AVEC LE CHAMP 'PASSWORD'. LEQUEL NE POURRAIT
PAS FONCTIONNER ?
<DIV CLASS='COL-MD-12'>
<DIV CLASS='FORM-GROUP'>
<LABEL FOR='INPUT-LOGIN-USERNAME' CLASS=''>USERNAME OR EMAIL</LABEL>
<INPUT NAME='USERNAME' PLACEHOLDER='YOUR USERNAME OR EMAIL' ID='INPUT-LOGIN-USERNAME'
TYPE='TEXT' CLASS='IS-UNTOUCHED IS-PRISTINE AV-INVALID FORM-CONTROL' VALUE=''>
</DIV>
<DIV CLASS='FORM-GROUP'>
<LABEL FOR='INPUT-LOGIN-PASSWORD' CLASS=''>PASSWORD</LABEL>
<INPUT NAME='PASSWORD' PLACEHOLDER='YOUR PASSWORD' ID='INPUT-LOGIN-PASSWORD'
TYPE='PASSWORD' CLASS='IS-UNTOUCHED IS-PRISTINE AV-INVALID FORM-CONTROL' VALUE=''>
</DIV>
<DIV CLASS='FORM-CHECK FORM-CHECK-INLINE'>
<LABEL CLASS='FORM-CHECK-LABEL'>
<INPUT NAME='REMEMBERME' ID='INPUT-LOGIN-REMEMBERME' TYPE='CHECKBOX' CLASS='IS-UNTOUCHED
IS-PRISTINE AV-VALID FORM-CHECK-INPUT' VALUE='FALSE'>
<SPAN>REMEMBER ME
</LABEL>
</DIV>
</DIV>
1. div + div
2. [@placeholder='Your password']
3. #input-login-password
4. div:nth-child(2)
Temps restant : 29 min 53 sec Version anglaise
https://hightest.nc/ressources/test-a4q-selenium.php 4/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
12 - LES LOGS DES TESTS AUTOMATISÉS ONT PLUSIEURS UTILITÉS DIRECTES. LAQUELLE N'EN FAIT PAS PARTIE ?
1. Aider les analystes de test à déterminer rapidement si une défaillance a été causée par le système à
tester ou non
2. Suivre les événements qui se produisent pendant l'exécution des tests
3. Dans le cadre de logiciels critiques pour la sureté ou pour le service rendu, fournir des informations
à des fins d'audit
4. Mettre en place un référentiel de bonnes pratiques de maintenabilité des tests
1. driver.close()
2. driver.dismiss()
3. driver.kill()
4. driver.quit()
14 - IL EXISTE PLUSIEURS FAÇONS DE CHANGER DE CADRE ('FRAME') SUR UNE PAGE WEB. LAQUELLE NE
POURRAIT PAS FONCTIONNER (EN PYTHON) ?
1. driver.switch_to.frame('beautiful_frame')
2. beautiful_frame = driver.find_element_by_name('beautiful_frame')
driver.switch_to.frame(beautiful_frame)
3. beautiful_frame = driver.find_elements_by_class_name('beautiful_frame')
driver.switch_to.frame(beautiful_frame)
4. beautiful_frame = driver.find_element_by_xpath("//*[@id='beautiful_frame'][contains(@class,
'frame')]")
driver.switch_to.frame(beautiful_frame)
15 - LES CAPTURES D'ÉCRAN ONT PLUSIEURS UTILITÉS AU SEIN D'UN PROJET DE TESTS AUTOMATISÉS.
Temps restant : 29 min 53 sec Version anglaise
LAQUELLE N'EN FAIT PAS PARTIE ?
https://hightest.nc/ressources/test-a4q-selenium.php 5/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
1. Prouver que les tests ont bien été effectués. Quel que soit le contexte, il convient toujours de fournir
une capture d'écran à chaque fois qu'une action a été réalisée sur le système à tester.
2. Analyser les défaillances détectées par les scripts de tests automatisés.
3. Aider les testeurs à déterminer la réussite d'un test lorsque ce test est très visuel et que la
détermination de la réussite ou de l'échec ne peut se faire qu'en visualisant l'image de l'écran.
4. Lorsqu'il s'agit de logiciels critiques pour la sûreté ou la mission, fournir des informations utiles lors
d'un audit des tests.
16 - SELENIUM PERMET NATIVEMENT DE VÉRIFIER DANS QUEL ÉTAT SE TROUVE UN ÉLÉMENT D'UNE PAGE WEB.
LEQUEL DES ÉTATS SUIVANTS NE PEUT PAS ÊTRE VÉRIFIÉ NATIVEMENT PAR SELENIUM ?
17 - QUELLES SONT LES DEUX MÉTHODES PERMETTANT DE FERMER UNE INVITE UTILISATEUR ?
1. dismiss() et close()
2. dismiss() et accept()
3. dismiss() et quit()
4. dismiss() et kill()
1. Le fait de remonter l’intelligence au niveau de l’architecture d’automatisation des tests et/ou du
framework d’automatisation plutôt qu’au niveau de chaque script individuel, notamment en utilisant des
wrappers.
2. Le fait de prévoir des logs précis et spécifiques, permettant de réduire l'effort de diagnostic en cas
d'échec du test, et donc l'effort global de correction en cas de faux positif.
3. Le fait d'éviter d'utiliser de chemins d'accès absolus lorsqu'on localise des éléments web avec XPath
Temps restant :
et sélecteurs CSS. 29 min 53 sec Version anglaise
https://hightest.nc/ressources/test-a4q-selenium.php 6/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest
4. Le fait de séparer chaque script de test dans un fichier dédié, lui-même dans un dossier dédié du
même nom que le fichier.
1. Les Page Objects permettent de créer du code réutilisable qui peut être partagé par plusieurs scripts
de test.
2. Les Page Objects permettent de réduire les coûts et les efforts de maintenance des scripts
d'automatisation des tests.
3. Les Page Objects séparent clairement les parties métier et les parties techniques de la conception
de l'automatisation des tests.
4. Les Page Objects utilisent des fichiers de données contenant à la fois les données de test et les
résultats attendus.
TERMINÉ !
Qu'appelle-t-on le 'shift-left' ?
1. Le fait de pousser plus de tests plus tôt dans le cycle de vie du développement
logiciel pour trouver et supprimer les défauts du code plus tôt.
2. Une méthode générale pour rendre libre une oeuvre (notamment un programme
informatique) et obliger toutes les versions modifiées ou étendues de ce programme à
être libres également
3. Une méthode de gestion de la production (notamment informatique) qui se concentre
sur la réduction des efforts inutiles (ou 'gaspillage').
4. Une méthode de test continu du logiciel quand celui-ci se trouve dans un
environnement de production.
Solution
Voir 1.1.
Les testeurs humains possèdent plusieurs atouts dont les tests automatisés sont
dénués. Lequel de ces atouts n'est pas propre aux humains ?
Solution
Voir 1.2. Les tests automatisés peuvent en effet eux aussi s'adapter : 'un script
automatisé peut avoir une intelligence intégrée par l'automaticien de tests via la
programmation'. Par exemple, il est possible de développer un test automatisé en lui
spécifiant : 'Si tu te rends sur la page et qu'il y a un bouton rouge, clique dessus ; et s'il
y a un bouton gris, survole-le.'. En revanche, en cas de comportement non anticipé par
le testeur (par exemple un bouton vert), les tests automatisés échoueront.
Solution
Voir 1.3. Un projet d'automatisation des tests réussi anticipe au plus tôt les efforts de
maintenance ; l'interface utilisateur peut ainsi changer avec relativement peu d'impact
sur l'efficacité globale du projet de tests automatisés. Attendre que l'interface soit 'figée'
priverait les parties prenantes des bénéfices qu'apporte l'automatisation des tests
lorsqu'elle est menée parallèlement au projet de développement du système à tester.
1. Les organisations sont souvent tellement préoccupées par les tests via l'interface
graphique qu'elles peuvent oublier que la pyramide des tests suggère que davantage
de tests unitaires/composants soient effectués.
2. Les tests fonctionnels dynamiques automatisés mettent généralement en
oeuvre des scénarios plus éloignés des comportements utilisateurs que ceux des
tests unitaires.
3. Lors du test d'un workflow dans un contexte d’intégration continue, les tests
fonctionnels dynamiques automatisés peuvent rendre le build beaucoup plus long que
prévu.
4. Les modifications apportées à l’interface utilisateur ont un impact sur les tests au
niveau du navigateur plus important que les tests au niveau unitaire ou de l'API.
Solution
Voir 1.4.
1. Couche d'adaptation des tests : fournit les objets et le code nécessaires à l'interface
avec le SUT (système testé) à différents niveaux
2. Couche de correspondance des tests : prend en charge la traçabilité entre les
cas de test manuels et les scripts de tests automatisés.
3. Couche de définition des tests : prend en charge la définition et l'implémentation des
cas de test et/ou des suites de tests.
4. Couche d'exécution des tests : supporte à la fois l'exécution des tests automatisés et
l'enregistrement des résultats.
Solution
Voir 1.5.
1. Taux de couverture des tests unitaires portant sur les classes utilisées par les
tests Selenium
2. Effort de test de régression qui a été économisé par l'automatisation.
3. Effort déployé par l'équipe d'automatisation en support à l'automatisation.
4. Couverture des User Stories (en projet agile)
Solution
Voir 1.6.
Solution
Voir 1.7.
Quel est le langage qui définit sémantiquement la structure d'une page web ?
1. XML
2. CSS
3. HTML
4. JavaScript
Solution
Voir 2.1.
Une application web de jeu en ligne affiche sur une page le classement des
joueurs. Quelle balise est la plus appropriée pour contenir la liste de ces joueurs
?
1. <ol>[...]</ol>
2. <ul>[...]</ul>
3. <li>[...]</li>
4. <br>[...]</br>
Solution
Voir 2.1.
1. //tr[contains(., 'Nicolas')]/following-sibling::td[3]
2. //td[contains(., 'Nicolas')]/following-sibling::td[3]
3. //td[contains(., 'Nicolas')]/following-sibling::td[2]
4. //tr[contains(., 'Nicolas')]/following-sibling::td[2]
Solution
Voir 2.2.
Les logs des tests automatisés ont plusieurs utilités directes. Laquelle n'en fait
pas partie ?
1. Aider les analystes de test à déterminer rapidement si une défaillance a été causée
par le système à tester ou non
2. Suivre les événements qui se produisent pendant l'exécution des tests
3. Dans le cadre de logiciels critiques pour la sureté ou pour le service rendu, fournir
des informations à des fins d'audit
4. Mettre en place un référentiel de bonnes pratiques de maintenabilité des tests
Solution
Voir 3.1.
Solution
Voir 3.2.
Il existe plusieurs façons de changer de cadre ('frame') sur une page web.
Laquelle ne pourrait pas fonctionner (en Python) ?
1. driver.switch_to.frame('beautiful_frame')
2. beautiful_frame = driver.find_element_by_name('beautiful_frame')
driver.switch_to.frame(beautiful_frame)
3. beautiful_frame = driver.find_elements_by_class_name('beautiful_frame')
driver.switch_to.frame(beautiful_frame)
4. beautiful_frame =
driver.find_element_by_xpath("//*[@id='beautiful_frame'][contains(@class, 'frame')]")
driver.switch_to.frame(beautiful_frame)
Solution
Les captures d'écran ont plusieurs utilités au sein d'un projet de tests
automatisés. Laquelle n'en fait pas partie ?
1. Prouver que les tests ont bien été effectués. Quel que soit le contexte, il
convient toujours de fournir une capture d'écran à chaque fois qu'une action a
été réalisée sur le système à tester.
2. Analyser les défaillances détectées par les scripts de tests automatisés.
3. Aider les testeurs à déterminer la réussite d'un test lorsque ce test est très visuel et
que la détermination de la réussite ou de l'échec ne peut se faire qu'en visualisant
l'image de l'écran.
4. Lorsqu'il s'agit de logiciels critiques pour la sûreté ou la mission, fournir des
informations utiles lors d'un audit des tests.
Solution
Voir 3.4.
Selenium permet nativement de vérifier dans quel état se trouve un élément d'une
page web. Lequel des états suivants ne peut pas être vérifié nativement par
Selenium ?
Solution
Voir 3.5.
Quelles sont les deux méthodes permettant de fermer une invite utilisateur ?
1. dismiss() et close()
2. dismiss() et accept()
3. dismiss() et quit()
4. dismiss() et kill()
Solution
Voir 3.8.
Solution
Voir 4.1.
Solution
Voir 4.2.
1. Les Page Objects permettent de créer du code réutilisable qui peut être partagé par
plusieurs scripts de test.
2. Les Page Objects permettent de réduire les coûts et les efforts de maintenance des
scripts d'automatisation des tests.
3. Les Page Objects séparent clairement les parties métier et les parties techniques de
la conception de l'automatisation des tests.
4. Les Page Objects utilisent des fichiers de données contenant à la fois les
données de test et les résultats attendus.
Solution
Voir 4.3.
05/01/2023 19:25 Quiz Selenium & Java - Hightest
2 - CETTE ERREUR EST SURVENUE AU MOMENT DE CLIQUER SUR UN BOUTON. QUE SIGNIFIE-T-ELLE ?
1. Le bouton est bien présent dans la page, mais il n'est pas cliquable.
2. Le bouton est absent de la page.
3. Le sélecteur du bouton était invalide.
4. Le navigateur devrait être mis à jour.
3 }
1. Rien du tout
2. Une pause de 3 secondes aura lieu.
3. Une pause de 3 millisecondes aura lieu.
4. Une erreur aura lieu.
1 PACKAGE UTILS;
2
3 PUBLIC ENUM COUNTRY {
4
5 FRANCE("FR"),
6 NEW_CALEDONIA("NC"),
7 PORTUGAL("PT") ;
8
9 PRIVATE STRING CODEPAYS;
10
11 PRIVATE COUNTRY(STRING CODEPAYS) {
12 THIS.CODEPAYS = "FR";
13 }
14
15 PUBLIC STRING GETCODEPAYS() {
16 RETURN THIS.CODEPAYS;
17 }
18 }
9 - POURQUOI CE SÉLECTEUR NE FONCTIONNERA PAS ? (CONNAÎTRE NOTRE CLASSE SELECTEUR N'A PAS
D'IMPORTANCE ICI.)
3 }
1. Le corps de cette méthode est identique au corps d'une autre méthode.
2. La valeur retournée par la méthode n'est pas du bon type.
3. La méthode n'est pas censée retourner une valeur.
4. Il manque une parenthèse.
1. La méthode devrait retourner une valeur, mais ce n'est pas le cas.
2. La méthode sera en erreur à chaque fois que le login attendu ne sera pas une chaîne de caractères
vide.
3. Le xPath est incorrect.
4. Il va y avoir systématiquement une erreur si plusieurs objets de la page correspondent à ce même
xPath.
14 - POURQUOI N'EST-IL PAS POSSIBLE DE VÉRIFIER QUE LE TITRE DU FILM 300 S'AFFICHE BIEN SUR LA PAGE ?
Temps restant :
QUESTION-15.JAVA 29 WITH
HOSTED min 56 sec
❤ BY GITHUB Version anglaise
VIEW RAW
https://hightest.nc/ressources/test-selenium-java.php 6/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest
1. La valeur affectée à la variable 'nomArticleConstate' n'est pas une String comme attendu, mais un
WebElement.
2. La valeur affectée à la variable 'nomArticleConstate' n'est pas une String comme attendu, mais un
tableau de String.
3. La valeur affectée à la variable 'nomArticleConstate' n'est pas une String comme attendu, mais un
tableau de WebElement.
4. La même variable est déclarée deux fois.
1. La variable nomArticleAttendu est une variable globale, qui ne peut donc pas être utilisée au sein
d'une méthode.
2. La variable nomArticleAttendu devrait être intervertie avec le premier argument.
3. La variable nomArticleAttendu n'a pas été déclarée du tout.
4. La variable nomArticleAttendu n'est pas de type String.
TERMINÉ !
Solution
La méthode findElement retourne un objet de type WebElement, alors que c'est une
String qui est attendue. La méthode getText(), ou getAttribute('value') pour les inputs,
aurait permis de retourner le bon type à partir de ce WebElement.
Cette erreur est survenue au moment de cliquer sur un bouton. Que signifie-t-elle
?
1. Le bouton est bien présent dans la page, mais il n'est pas cliquable.
2. Le bouton est absent de la page.
3. Le sélecteur du bouton était invalide.
4. Le navigateur devrait être mis à jour.
Solution
Cette erreur peut survenir lorsqu'un bouton désactivé est cliqué, par exemple au sein
d'un formulaire dont les champs obligatoires n'ont pas été remplis.
Solution
Il n'est pas possible en Java de comparer un int et une String sans passer par une
conversion (avec les méthodes Integer.parseInt() ou String.valueOf().
1. Rien du tout
2. Une pause de 3 secondes aura lieu.
3. Une pause de 3 millisecondes aura lieu.
4. Une erreur aura lieu.
Solution
Solution
Solution
Solution
Solution
Solution
Solution
Solution
Ce fil de discussion propose quelques moyens de contournement.
Solution
Solution
Pour récupérer le contenu d'un input, il faut utiliser non pas la méthode getText() mais
getAttribute('value').
Pourquoi n'est-il pas possible de vérifier que le titre du film 300 s'affiche bien sur
la page ?
1. Parce que le type attendu est 'String' et non 'int'.
2. Parce que la valeur saisie est trop courte.
3. Parce que les deux méthodes ont exactement le même nom.
4. Parce qu'il manque un argument pour correctement appeler la méthode
assertEquals().
Solution
Solution
Solution
1. La variable nomArticleAttendu est une variable globale, qui ne peut donc pas être
utilisée au sein d'une méthode.
2. La variable nomArticleAttendu devrait être intervertie avec le premier argument.
3. La variable nomArticleAttendu n'a pas été déclarée du tout.
4. La variable nomArticleAttendu n'est pas de type String.
Solution
1. Il manque un point-virgule.
2. La méthode verifierDonneesArticle() ne fait rien d'autre que d'appeler d'autres
méthodes.
3. La méthode assertEquals() ne peut pas être utilisée pour comparer deux 'int'.
4. Il y a une parenthèse en trop.
Solution
Solution
Implicit wait time is applied to all elements in your code while Explicit waits
are applied only to a single element for a specified amount of time.
True False
https://blog.testproject.io/quiz/interview/ 1/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject
wait.until(ExpectedConditions.presenceOfElementLocated(by));
Explicit wait
Implicit wait
Google Chrome
Internet Explorer
Opera
Mozilla Firefox
All of the above
element.click(x, y);
Selenium WebDriver does not support this functionality
Using the Actions class' method moveToElement(element, xOffset, yOffset)
What would be the ideal way to identify an element without ID or Class ?
<html>
<head>
<button>Test</button>
</head>
</html>
https://blog.testproject.io/quiz/interview/ 2/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject
By.xpath("//button[contains(., 'Test')]")
By.text("Sample'")
By.xpath("//button[contains(text(), 'Test')]")
It is not possible to locate elements without an ID or Class name
<div class="container">
<div class="title"></div>
</div>
<div class="container title">
</div>
Using Selenium WebDriver, how would you select only the element with the
2 classes: 'container' and 'title' ?
Email Email
https://blog.testproject.io/quiz/interview/ 3/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject
Submit
Appium Quiz
Leave a Reply
You must be logged in to post a comment.
Most Popular
Editor's Picks
Resources
https://blog.testproject.io/quiz/interview/ 4/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject
COMMUNITY
https://blog.testproject.io/quiz/interview/ 5/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject
BLOG CATEGORIES
COMPANY
https://blog.testproject.io/quiz/interview/ 6/6
Question:
1° Implicit wait time is applied to all elements in your code while Explicit waits
are applied only to a single element for a specified amount of time.
Correct Answer: True
Question:
2° Data Driven Testing (DDT) is a methodology in automated testing to test only a single
set of Test Data. Correct Answer: False
Question:
Question:
wait.until(ExpectedConditions.presenceOfElementLocated(by));
Question:
Question:
Correct Answer: Using the Actions class' method moveToElement(element, xOffset, yOffset)
Question:
7° What would be the ideal way to identify an element without ID or Class ?
By.xpath("//button[contains(., 'Test')]") Correct Answer: By.xpath("//button[contains(.,
'Test')]").By.xpath("//button[contains(text(), 'Test')]")
Question:
Using Selenium WebDriver, how would you select only the element with the 2
classes: 'container' and 'title' ?
Automation Trivia
A tool must not be unsafe to use. Hammers have handles and screwdrivers have hilts
to help increase grip. It is of course possible for a person to injure himself with one of
these tools, but that injury would only be due to his incompetence, not the design of the
tool. - Isaac Asimov
4. Which of the following is the correct ‘Webdriver’ command to “delete all cookies in the
browser”?
a) Driver.deleteAllCookies()
b) Driver.manage().deleteCookies()
c) Driver.manage().deleteAllCookies()
d) Driver.deleteCookies()
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 1/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
5. In webdriver, which of the following is a valid select statement that selects a value from a
dropdown element?
a) All of the listed options
b) selectByIndex()
c) selectByValue()
d) selectByVisibleText()
7. In webdriver, which of the following commands retrieves the text of html element?
a) selectText()
b) getText()
c) getElementText()
d) getText(WebElement)
8. In webdriver, which command takes you forward by one page on the browser’s history?
a) navigate.forward()
b) Navigate.forward()
c) navigate().forward()
d) Navigate.forward
e) navigate_forward()
10. Which of the following Selenium API enables running Selenium 1.0 tests in web driver?
a) Selenium RC
b) None of the listed options
c) Webdriver
d) WebDriverBackedSelenium
11. In WebDriver, which command can be used to enter values onto text boxes? Select the best
answer.
a) type()
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 2/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
b) selenium.type()
c) driver.type("text")
d) sendKeys()
e) sendKeys("text")
12. Which command should be used to ensure Selenium applies wait time for all UI elements
in the script?
a) Explicit wait
b) Fluent Wait
c) Implicit Wait
d) Sleep
13. Which of the following is the correct option to close all the opened browser sessions at
one step?
a) Driver.close()
b) Driver.quit()
c) Driver.closeAll()
d) Driver.exit()
15. Which of the following will terminate the test when the check fails
a) Verify
b) Assert
17. Which command to be used to get the text from Alert message popup
a) Alert alert = driver.switchTo().alert();
String message = alert.getText();
b) SwitchAlert alert = driver.switchalert();
String message = alert.getText();
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 3/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
19. Implicit wait time is applied to all elements in your script and Explicit wait time is applied
only for particular specified element.
a) True
b) False
a) Output is Name 1
b) Output is Name 2
c) CSS selector syntax is incorrect
23. In webdriver, what is the method that counts the number of elements?
a) driver.getCountOfElements()
b) driver.findElement(By.id("search")).getCount()
c) driver.findElements(By.id("search")).size()
d) driver.findElements(By.id("search")).length()
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 4/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
25. Identify the steps to instantiate the Chrome driver in correct sequence
a) 1. Using System Property set method get the path of chrome driver
2. Initialize chrome driver Object with capabilities object as argument
3. Open the URL
4. Set the capabilities of chrome browser
b) 1. Using System Property set method get the path of chrome driver
2. Set the capabilities of chrome browser
3. Initialize chrome driver Object with capabilities object as argument
4. Open the URL
c) 1. Using System Property set method get the path of chrome driver
2. Set the capabilities of chrome browser
3. Open the URL
4. Initialize chrome driver Object with capabilities object as argument
d) 1. Set the capabilities of chrome browser
2. Initialize chrome driver Object with capabilities object as argument
3. Using System Property set method get the path of chrome driver
4. Open the URL
26. Identify the valid command to handle pop ups in chrome browser
a) Alert objAlert = driver.switchTo().alert();); objAlert.accept();
b) driver.findElement(By.id(‘AlertId’)).sendkeys(Keys.Enter);
c) Alert objAlert = new Alert(driver); objAlert.accept();
28. Select the variation which locates elements by the value of the “name” attribute in Web
driver Selenium
a) By.name
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 5/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
b) By.nametag
c) By.tagname
d) By.nametags
29. Select the Get command which fetches the inner text of the element that you specify in
Web driver Selenium.
a) getinnerText()
b) get_in_Text()
c) get_inner_Text()
d) getText()
32. To run a test on Firefox browser, you must have which of the following?
a) Firefox plug-ins are installed
b) Only Firefox browser is installed
c) GeckoDriver is installed, similar to IEDriver and ChromeDriver setup
d) Both GeckoDriver and Firefox browser are installed
33. Identify the correct code snippet to double click an element using selenium from the
following:
a) WebElement el = driver.findElement(By.id(“Element”));
Actions builder = new Actions(driver)
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 6/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
Builder.doubleClick().build().perform()
b) WebElement el = driver.findElement(by.id(“ElementID”))
Actions builder = new Actions(driver0;
Buider.doubleClick().build()
c) WebElement el = driver.findElemet(by.id(“ElementID”))
Actions builder = new Actions(driver)
Buider.doubleClick().build()
d) WebElement el = driver.findElement(By.id(“ElementID”)
Actions builder = new Actions(driver)
Builder.doubleClick(el).build()perform()
34. Which of the following is the correct Webdriver statement to retrieve the row count of a
Table?
a) All of the listed options
b) Driver.FindElements(By.Xpath(“//table[@id=’tableID’]/tr”)).size();
c) Driver.FindElements(By.Xpath(“//table[@id=’tableID’]/tr”)).getrowcount();
d) Driver.FindElements(By.Xpath(“//table[@id=’tableID’]/tr”)).getcount();
35. Which of the following features are applicable for both Test NG and Junit?
I) Suite Test
II) Group Test
III) Parameterized Test object
IV) Dependency Test
Select One:
a) I, II, III IV
b) I and II
c) I
d) I and III
Example:
Wait wait = new FluentWait(driver)
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 7/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
1. Ignores NoSuchElementException
2. Automatically adds NoSuchElementException
3. Defines the maximum amount of time to wait for a condition
4. Frequency with which to check the condition
Identify the valid options based on above example
a) Option 1,3 & 4
b) Option 3 & 4
c) Option 2,3 & 4
driver.findElement(By.xpath(“//table/tr[1]/td”)).getText();
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 8/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
42. Which method is used when you want to verify whether a certain check box, radio button,
or option in a drop-down box is selected in Web driver Selenium
a) is_Selected()
b) isSelect()
c) isSelected()
d) is_Select()
45. To delete a cookie we need to call the deleteCookie method, passing in two parameters.
a) The first parameter is the name of the cookie, and the second parameter is where it was
created.
b) The first parameter is where it was created, and the second parameter is the name of
cookie.
c) None of these
46. Selects all the parent, grandparent, and so on of the element is related to which axis name
in Selenium:
a) Ancestor
b) Preceding
c) Parent
d) All of these.
47. You have to use ‘Xpath’ to locate the following input element:
<input id=”fk-top-search-box” class=”search-bar-text fk-font-13 ac_input” type=”text”
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 9/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
48. Select the method which performs a context-click (right click) at the current mouse
location.
a) click_Context()
b) context.Click()
c) contextClick()
d) context_Click()
50. Which of the following API enables running Selenium 1.0 tests in Webdriver
a) Webdriver
b) None of the listed options
c) WebdriverbackedSelenium
d) Selenium RC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
c c d c a b b c b d e c b b b b a b a d
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
a c c c b a c a d c a d d b c d a b b b
41 42 43 44 45 46 47 48 49 50
a c b a a a d c a c
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 10/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
1. Identify the invalid options about Selenium IDE a) It is a Firefox add-on and by using
selenium IDE user can record and playback test cases in Firefox browser b) Tester can export
…
the test cases from selenium IDE in Java Language only c) Tester can insert breakpoints in IDE
SELENIUMHOME
Steps to get OTIClient.jar file to perform operations within QC 1) Open the HP Quality Center in
IE browser and navigate to QC Login page 2) Navigate to the local path of the HP folder to get
the OTAClient.dll (Mostly the Path would be “C:\Users\<UserName>\AppData\Local\HP\ALM-…
SELENIUMHOME
Powered by Blogger
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 11/12
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer
SARAVANAN
VISIT PROFILE
Archive
Labels
Report Abuse
seleniumtrivia.blogspot.com/2017/08/selenium-interview-questions-with_31.html 12/12
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1
Plus
Ramesh Kudikala
Selenium Ques $ Ans -1
View my complete profile
· Grid: With the help of Grid you can distribute tests on multiple machines so that test can be run parallel Core Java - Collections -1
which helps in cutting down the time required for Manual Testing Stuff
Selenium ques $ans -4
· running in browser test suites
Selenium que $ans -3
2) What is Selenium 2.0 ?
selenium que $ans -2
Web testing tools Selenium RC and WebDriver are consolidated in single tool in Selenium 2.0 Selenium Ques $ Ans -1
50- Selenium Webdriver interview Ques
3) How will you find an element using Selenium? ans...
50 - Selenium Webdriver interview Ques
In Selenium every object or control in a web page is referred as an elements, there are different ways to 20 Java Collections Interview Questions
find an element in a web page they are What are the challenges of Selenium Au
Selenium Webdriver interview Question
· ID
· Name
· Tag
· Attribute
· CSS
· Linktext
· PartialLink Text
· Xpath etc
4) List out the test types that are supported by Selenium?
a) Functional
b) Regression
For post release validation with continuous integration automation tool could be used
a) Jenkins
b) Hudson
d) CruiseCont
5) Explain what is assertion in Selenium and what are the types of assertion?
Assertion is used as a verification point. It verifies that the state of the application conforms to what is
expected. The types of assertion are “assert” , “verify” and “waifFor”.
SeleniumSuite
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 1/5
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1
6) Mention what is the use of X-path?
X-Path is used to find the WebElement in web pages. It is also useful in identifying the dynamic elements.
Single slash ‘/ ’
TypeKeys() will trigger JavaScript event in most of the cases whereas .type() won’t. Type key populates the
value attribute using JavaScript whereas .typekeys() emulates like actual user typing
In JAVA a special form of syntactic meta-data can be added to Java source code, this is know as
Annotations. Variables, parameters, packages, methods and classes are annotated some of the JUnit
annotations which can be useful are
· Test
· Before
· After
· Ignore
· BeforeClass
· AfterClass
· RunWith
12) While using click command can you use screen coordinate?
To click on specific part of element, you would need to use clickAT command. ClickAt command accepts
element locator and x, y co-ordinates as arguments-
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 2/5
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1
· Selenium is used specially for testing web based applications while QTP can be used for testing client server
application also
· Selenium supports Firefox, IE, Opera, Safari on operating systems like Windows, Mac, linux etc. however
QTP is limited to Internet Explorer on Windows.
· Selenium supports many programming languages like Ruby, Perl, Python whereas QTP supports only VB
script
15) What are the four parameter you have to pass in Selenium?
· Host
· Port Number
· Browser
· URL
16) What is the difference between setSpeed() and sleep() methods?
Thread.sleep () : It will stop the current (java) thread for the specified period of time. Its done only once
SetSpeed () : For specific amount of time it will stop the execution for every selenium command.
· Runs each command after setSpeed delay by the number of milliseconds mentioned in set Speed
This command is useful for demonstration purpose or if you are using a slow web application
17) What is same origin policy? How you can avoid same origin policy?
The “Same Origin Policy” is introduced for security reason, and it ensures that content of your site will
never be accessible by a script from another site. As per the policy, any code loaded within the browser
can only operate within that website’s domain.
To avoid “Same Origin Policy” proxy injection method is used, in proxy injection mode the Selenium Server
acts as a client configuredHTTP proxy , which sits between the browser and application under test and
then masks the AUT under a fictional URL
18) What is heightened privileges browsers?
The purpose of heightened privileges is similar to Proxy Injection, allows websites to do something that are
not commonly permitted. The key difference is that the browsers are launced in a special mode called
heightened privileges. By using these browser mode, Selenium core can open the AUT directly and also
read/write its content without passing the whole AUT through the Selenium RC server.
element.submit () ;
Alternatively you can use click method on the element which does form submission
20) What are the features of TestNG and list some of the functionality in TestNG which makes it
more effective?
TestNG is a testing framework based on JUnit and NUnit to simplify a broad range of testing needs, from
unit testing to integration testing. And the functionality which makes it efficient testing framework are
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 3/5
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1
· Ability to re-execute failed test cases
21) Mention what is the difference between Implicit wait and Explicit wait?
Implicit Wait: Sets a timeout for all successive Web Element searches. For the specified amount of time it
will try looking for element again and again before throwing a NoSuchElementException. It waits for
elements to show up.
22) Which attribute you should consider throughout the script in frame for “if no frame Id as well as
no frame name”?
You will ned to switch to each and every frame and search for locator which we want.
23) Explain what is the difference between find elements () and find element () ?
It finds the first element within the current page using the given “locating mechanism”. It returns a single
WebElement
findElements () : Using the given “locating mechanism” find all the elements within the current page. It
returns a list of web elements.
· @Before public void method() – It will perform the method () before each test, this method can prepare the
test
· @Test public void method() – Annotations @Test identifies that this method is a test method environment
· @After public void method()- To execute a method before this annotation is used, test method must start with
test@Before
25) Explain what is Datadriven framework and Keyword driven?
Datadriven framework: In this framework, the test data is separated and kept outside the Test Scripts,
while test case logic resides in Test Scripts. Test data is read from the external files ( Excel Files) and are
loaded into the variables inside the Test Script. Variables are used for both for input values and for
verification values.
Keyworddriven framework: The keyword driven frameworks requires the development of data tables and
keywords, independent of the test automation. In a keyword driven test, the functionality of the application
under test is documented in a table as well as step by step instructions for each test.
26) Explain how you can login into any site if it’s showing any authentication popup for password
and username?
· Syntax-http://username:password@url
· ex- http://creyate:tom@www.gmail.com
27) Explain how to assert text of webpage using selenium 2.0 ?
WebElement el = driver.findElement(By.id(“ElementID”))
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 4/5
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1
· Borland Silk test is not a free testing tool · Selenium is completely free test automation tool
· Silk test supports only Internet Explorer · Selenium supports many browsers like Internet Explorer,
and Firefox · Firefox, Safari, Opera and so on
An object repository is an essential entity in any UI automations which allows a tester to store all object that
will be used in the scripts in one or more centralized locations rather than scattered all over the test scripts.
Selenium Grid sent the tests to the hub. These tests are redirected to Selenium Webdriver, which launch
the browser and run the test. With entire test suite, it allows for running tests in parallel.
Yes. But not as effectively as a dedicated performance testing tool like Loadrunner.
No comments:
Post a Comment
To leave a comment, click the button below to sign in with Blogger.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 5/5
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
Plus C
Ramesh Kudikala
selenium que $ans -2
View my complete profile
Question 7: What all different element locators are available with Selenium 2.0?
Answer: Selenium 2.0 uses same set of locators which are used by Selenium 1.0 – id, name, css, XPath
but how Selenium 2.0 accesses them is different. In case of Selenium 1.0 you don’t have to specify a
different method for each locator while in case of Selenium 2.0 there is a different method available to use a
different element locator. Selenium 2.0 uses following method to access elements with id, name, css and
XPath locator –
driver.findElement(By.id("HTMLid"));
driver.findElement(By.name("HTMLname"));
driver.findElement(By.cssSelector("cssLocator"));
driver.findElement(By. className ("CalssName”));
driver.findElement(By. linkText ("LinkeText”));
driver.findElement(By. partialLinkText ("PartialLink”));
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 1/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
driver.findElement(By. tagName ("TanName”));
driver.findElement(By.xpath("XPathLocator));
Question 15: How to count total number of rows of a table using Selenium 2.0?
Answer:
List {WebElement} rows = driver.findElements(By.className("//table[@id='tableID']/tr"));
int totalRow = rows.size();
Question 19: How to assert text assert text of webpage using selenium 2.0?
Answer:
WebElement el = driver.findElement(By.id("ElementID"));
//get test from element and stored in text variable
String text = el.getText();
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 2/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
//get test from element and stored in text variable
String attributeValue = el. getAttribute("AttributeName") ;
Html unit API is GUI less browser for java developer, using WebClent class we can send request to
application server and verify response header status.
Below code, I used in my webdriver script to verify response 200 of web application
//verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
//verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 3/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
In below example I have created a sample script in which first I captured a Google home page screen shot
and saved (GoogleInput.jpg) into my project, Another screen shot “GoogleOutput.jpg” captured of same
page at test executing time and saved into project. I compared both images if they are not same then test
will script fail.
Here is sample code for same
package com.test;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 4/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
}
}
}
else
matchFlag = false;
Assert.assertTrue(matchFlag, "Images are not same");
}
}
Road to handle http authentication in webdriver
One of my applications had Http authentication for security purpose and I had need to automate using
webdriver. As we know http authentication is not a part of DOM object so we cannot handle it using
webdriver. Here is approach to handle such type situation.
We need to pass http credential with URL to skip http popup authentication window. Below is URL format.
http://username:passwork@applicationURL
driver.get(“http://username:passwork@applicationURL”)
After using above approach, http authentication popup window disappear. But in Internet explorer, it raise
error with message “wrong format url”. To accept same type url in internet explorer browser we need to add
a DWORD value named exploere.exe and iexplore.exe with value data 0 in below registry.
To open registry, open "regeidt" from run command.
1. For all users of the program, set the value in the following registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
2. For the current user of the program only, set the value in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
3. If you are using 64 bit machine, set the value in the following registry key.
HKEY_CURRENT_USER\Software\WOW6432Node\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
2. Pause video
document.getElementById("Video ID").pause() ;
3. To check video is paused or not use below code
document.getElementById("Video ID").Paused;
4. To increase volume
document.getElementById("Video ID").volume=0.5;
5. To reload video
document.getElementById("Video ID").load();
6. To replay from stating or forward and back playing video. You can set current playing time.
document.getElementById("Video ID").currentTime=0
document.getElementById("Video ID").currentTime=10
document.getElementById("Video ID").currentTime=20
7. To check video is muted.
document.getElementById("Video ID").muted
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 5/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
6 public void testVideo() throws InterruptedException
7 {
8 driver = new FirefoxDriver();
9 driver.manage().window().maximize();
10 driver.get("http://www.w3.org/2010/05/video/mediaevents.html");
11 JavascriptExecutor js = (JavascriptExecutor) driver;
12
13 //play video
14 js .executeScript("document.getElementById(\"video\").play()");
15 Thread.sleep(5000);
16
17 //pause playing video
18 js .executeScript("document.getElementById(\"video\").pause()");
19
20 //check video is paused
21 System.out.println(js .executeScript("document.getElementById(\"video\").paused"));
22
23 js .executeScript("document.getElementById(\"video\").play()");
24
25 // play video from starting
26 js .executeScript("document.getElementById(\"video\").currentTime=0");
27 Thread.sleep(5000);
28
29 //reload video
30 js .executeScript("document.getElementById(\"video\").load()");
31 }
32 }
?
1 GraphicsConfiguration gc = GraphicsEnvironment
2 .getLocalGraphicsEnvironment()
3 .getDefaultScreenDevice()
4 .getDefaultConfiguration();
5
6
7 ScreenRecorder screenRecorder = new ScreenRecorder(gc,
10 CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
11 DepthKey, 24, FrameRateKey, Rational.valueOf(15),
12 QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60),
13 new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
14 FrameRateKey, Rational.valueOf(30)),null);
4. Need to call “screenRecorder.start()” methods at starting of your test scripts and
"screenRecorder.stop()” at the end of execution.
5. Below is complete test script example
?
1 package com.TestScripts;
2
3 import java.awt.*;
4 import java.io.File;
5 import org.monte.media.Format;
import org.monte.media.math.Rational;
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 6/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
6 import org.monte.screenrecorder.ScreenRecorder;
7 import org.openqa.selenium.By;
8 import org.openqa.selenium.WebDriver;
9 import org.openqa.selenium.WebElement;
10 import org.openqa.selenium.firefox.FirefoxDriver;
11 import static org.monte.media.AudioFormatKeys.*;
12 import static org.monte.media.VideoFormatKeys.*;
13
14 public class VideoReord {
15 private ScreenRecorder screenRecorder;
16
17 public static void main(String[] args) throws Exception {
18
19 VideoReord videoReord = new VideoReord();
20 videoReord.startRecording();
21
22 WebDriver driver = new FirefoxDriver();
23 driver.get("http://www.google.com");
24
25 WebElement element = driver.findElement(By.name("q"));
26 element.sendKeys("testing");
27 element.submit();
28 System.out.println("Page title is: " +driver.getTitle());
29 driver.quit();
30 videoReord.stopRecording();
31 }
32
33
34 public void startRecording() throws Exception
35 {
36
37 GraphicsConfiguration gc = GraphicsEnvironment
38 .getLocalGraphicsEnvironment()
39 .getDefaultScreenDevice()
40 .getDefaultConfiguration();
41
42 this.screenRecorder = new ScreenRecorder(gc,
43 new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
44 new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
45 CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
46 DepthKey, 24, FrameRateKey, Rational.valueOf(15),
47 QualityKey, 1.0f,
48 KeyFrameIntervalKey, 15 * 60),
49 new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
50 FrameRateKey, Rational.valueOf(30)),
51 null);
52 this.screenRecorder.start();
53
54 }
55
56 public void stopRecording() throws Exception
57 {
58 this.screenRecorder.stop();
59 }
60 }
61
6. After execution test script, video file is generated under “Video” folder of current user folder in
Windows machine and “Movies” folder on Mac machine.
I am getting some comments for saving video in a desire location, I am going to update my post as
Michael’s suggestion. Thanks again for his help.
If you need to save video file in desire location, then you need to override “createMovieFile” function of
“ScreenRecorder” class class for creating a new folder and file. For this you need to create another class
like “SpecializedScreenRecorder” and extend “ScreenRecorder” class as below:
?
1 package com.test;
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 7/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
2
3 import java.awt.AWTException;
4 import java.awt.GraphicsConfiguration;
5 import java.awt.Rectangle;
6 import java.io.File;
7 import java.io.IOException;
8 import java.text.SimpleDateFormat;
9 import java.util.Date;
10 import org.monte.media.Format;
11 import org.monte.media.Registry;
12 import org.monte.screenrecorder.ScreenRecorder;
13
14 public class SpecializedScreenRecorder extends ScreenRecorder {
15
private String name;
16
17
public SpecializedScreenRecorder(GraphicsConfiguration cfg,
18
Rectangle captureArea, Format fileFormat, Format screenFormat,
19
Format mouseFormat, Format audioFormat, File movieFolder,
20
String name) throws IOException, AWTException {
21
super(cfg, captureArea, fileFormat, screenFormat, mouseFormat,
22
audioFormat, movieFolder);
23
this.name = name;
24
}
25
26
@Override
27 protected File createMovieFile(Format fileFormat) throws IOException {
28
if (!movieFolder.exists()) {
29
movieFolder.mkdirs();
30
} else if (!movieFolder.isDirectory()) {
31
throw new IOException("\"" + movieFolder + "\" is not a directory.");
32
}
33
34
SimpleDateFormat dateFormat = new SimpleDateFormat(
35
"yyyy-MM-dd HH.mm.ss");
36
37
return new File(movieFolder, name + "-" + dateFormat.format(new Date()) + "."
38
+ Registry.getInstance().getExtension(fileFormat));
39
}
40
}
41
Now you need to create object of “SpecializedScreenRecorder” instead of creating “Screen” class object.
?
1 package com.test;
2
3 import java.awt.*;
4 import java.io.File;
5 import org.monte.media.Format;
6 import org.monte.media.math.Rational;
7 import org.monte.screenrecorder.ScreenRecorder;
8 import org.openqa.selenium.By;
9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.WebElement;
11 import org.openqa.selenium.firefox.FirefoxDriver;
12 import static org.monte.media.AudioFormatKeys.*;
13 import static org.monte.media.VideoFormatKeys.*;
14
15 public class VideoReord {
17
18 public static void main(String[] args) throws Exception {
19
20 VideoReord videoReord = new VideoReord();
21 videoReord.startRecording();
22
23 WebDriver driver = new FirefoxDriver();
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 8/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
24 driver.get("http://www.google.com");
25
26 WebElement element = driver.findElement(By.name("q"));
27 element.sendKeys("testing");
28 element.submit();
29 System.out.println("Page title is: " + driver.getTitle());
30 driver.quit();
31 videoReord.stopRecording();
32 }
33
34
35 public void startRecording() throws Exception
36 {
37 File file = new File("D:\\Videos");
38
39 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
40 int width = screenSize.width;
41 int height = screenSize.height;
42
43 Rectangle captureSize = new Rectangle(0,0, width, height);
44
45 GraphicsConfiguration gc = GraphicsEnvironment
46 .getLocalGraphicsEnvironment()
47 .getDefaultScreenDevice()
48 .getDefaultConfiguration();
49
50 this.screenRecorder = new SpecializedScreenRecorder(gc, captureSize,
51 new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
52 new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
53 CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
54 DepthKey, 24, FrameRateKey, Rational.valueOf(15),
55 QualityKey, 1.0f,
56 KeyFrameIntervalKey, 15 * 60),
57 new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
58 FrameRateKey, Rational.valueOf(30)),
59 null, file, "MyVideo");
60 this.screenRecorder.start();
61
62 }
63
64 public void stopRecording() throws Exception
65 {
66 this.screenRecorder.stop();
67 }
68 }
Above code explanation: Create a File class object and pass path where you want to save your video
File file = new File("D:\\Videos");
Create dimension of your screen to capture video, I have created object for default screen.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
Rectangle captureSize = new Rectangle(0,0, width, height);
Now Create object of “SpecializedScreenRecorder” and pass Rectangle object, File object, and file name
as a last argument and rest are same.
Run your test, you will see that a video will generate under your desire location.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 9/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
BufferedInputStream fileToParse = new BufferedInputStream(url.openStream());
PDFParser pdfParser = new PDFParser(fileToParse);
pdfParser.parse();
After applying above code, you can store all pdf file content into “pdftxt” string variable. Now you can verify
string by giving in put. As if you want to verify “Selenium Or Webdiver” text. Use below code.
Assert.assertTrue(pdftxt.contains(“Selenium Or Webdiver”))
Hope this post will help to verify web application PDF content.
http://4.bp.blogspot.com/-sV3E2LDXa50/U7heF0V4G-
I/AAAAAAAAAoo/WnhstOAXZWg/s1600/TestNGEclipse.JPG
Setup Job:
Create new job in Jenkins by following below steps. In this I am integrating Webdriver TestNg suite with Ant
build tool.
1. Go to Jenkins home page and click on “New Item”
2. Enter item name, select check box as per your requirement and click on OK button.
3. Enter required field, As I am using ant tool so I click on “Add Build steps” and select “Invoke Ant”
http://1.bp.blogspot.com/-
HrjHun6ZYqM/U7heCul6NSI/AAAAAAAAAoE/SybFScdeKOo/s1600/JenkinsTestNG1.JPG
http://2.bp.blogspot.com/-5UNu4ArJSMQ/U7heDqhkfrI/AAAAAAAAAoY/3qksiu62yC4/s1600/JenkinsTe
stNG4.jpg
3.Click on build link for testng report, like above “Build #3” you should see published report.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 10/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
http://4.bp.blogspot.com/-8tGOqoFSM80/U7heE_gT5yI/AAAAAAAAAok/EKs1d8MfHrU/s1600/JenkinsT
estNG6.jpg
Launching Hub:
Open command prompt and got to your selenium server jar file and run command:
http://3.bp.blogspot.com/-6e5QQ5vGanY/US5narJDZeI/AAAAAAAAAA4/A2yELBbvGsI/s400/hub.jpg
Launching Nodes:
Open two command prompt and go to your selenium server jar file and run below command:
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5555 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=13
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5556 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=firefox,platform=XP,version=12
http://2.bp.blogspot.com/-NUk1_WVnKV8/US5nxbFed8I/AAAAAAAAABA/i-jTeBxj9ks/s400/node1.jpg
http://4.bp.blogspot.com/-HYOfL76ph84/US5n6-zfQFI/AAAAAAAAABI/CRXV7jxbmpQ/s400/node2.JPG
Note: if you want to run Node on different machine then replace “localhost” to your system IP address
where Hub is running.
http://4.bp.blogspot.com/-Vuw8v0oHBC4/US5oTBRueyI/AAAAAAAAABQ/Enj9AgFqI_A/s400/url.JPG
1. Run below command in on your console to launch Grid hub console:
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 4444 -role hub
2. Open two console and run below command to launch and register node with Grid hub.
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5555 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5556 -role webdriver -hub
http://192.168.1.22:4444/grid/register -browser browserName=iexplore,platform=WINDOWS
Replace local host to system IP of Hob machine. If you want to launch node in different machine.
Test script::
Put “xmlrunner.py” downloaded file in your project and create a scripts as like below script.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 11/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
import sys
from xmlrunner import *
class Grid2(unittest.TestCase):
capabilities = None
def setUp(self):
self.driver = webdriver.Remote(desired_capabilities={
"browserName": browser,
"platform":platform,
"node":port
})
print "set up executed"
def test_example(self):
self.driver.get("http://www.google.com")
print "open google url"
self.assertEqual(self.driver.title, "Google")
print "verify title"
self.driver.find_element_by_id("gbqfq").clear()
self.driver.find_element_by_id("gbqfq").send_keys("testing")
print "enter text in serach field"
self.driver.find_element_by_id("gbqfb").click()
print "click on search button"
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
args = sys.argv
port = args[1]
platform = args[2]
browser = args[3]
suite = unittest.TestSuite()
suite.addTest(Grid2('test_example'))
runner = XMLTestRunner(file('results_ExampleTestCase_%s.xml' % (browser), "w"))
runner.run(suite)
Execution:
Open two consoles go to your test scripts project and run below command one by one.
Hub:
java -jar selenium-server-standalone-2.29.0.jar -host localhost -port 4444 -role hub
Nodes:
java -jar selenium-server-standalone-2.29.0.jar -host localhost -port 5555 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=iexplore,platform=XP,version=8
java -jar selenium-server-standalone-2.29.0.jar -host localhost -port 5556 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=firefox,platform=XP,version=13
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 12/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
2. Run test case parallel: This “WebDriverGrid2Test “ example will be run test case on firefox and internet
explorer on version 8 and 13 respectively.
package com.test;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 13/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
capability.setBrowserName("iexplore");
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
capability.setVersion(version);
}
if(os.equals("WINDOWS")){
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
}
else if(os.equals("XP")){
capability.setPlatform(org.openqa.selenium.Platform.XP);
}
else if(os.equals("Linux")){
capability.setPlatform(org.openqa.selenium.Platform.LINUX);
}
else{
capability.setPlatform(org.openqa.selenium.Platform.ANY);
}
return capability;
}
}
4. Rigth click on Suite.xml file, select “Run As” and click on TestNG Suite options
5. Now test script is executed on both browser and version combination. execution log on eclipse look like
as below:
http://2.bp.blogspot.com/-
BBcCslNqHGM/UTN9suUpZDI/AAAAAAAAAC4/nG2K295HW_A/s400/Report.JPG
.
Webdriver C# test scripts execution using Grid2
Nunit framework is not support parallel execution of driver test scripts using Grid. If we use MbUuit
framework then we can accomplish parallel execution of test scripts against Grid2. For set up MbUnit you
can see “MbUnit Framework”
Test scripts setup :
1. Add reference Gallio and MbUnit ddl file to your Webdriver project from installed Gallio folder.
2. Add below code in project’s “AssemblyInfo.cs” file.
using MbUnit.Framework;
[assembly:DegreeOfParallelism(2)]
[assembly:Parallelizable(TestScope.All)]
3. We need to add below code for MbUnit framework in test scripts.
using MbUnit.Framework;
add [Parallelizable] annotation on test case lavel ass I added in belowtest scripts.
4. I have created two test one “GridTest1.cs” file for internet explorer and “GridTest2.cs” file for firefox
browser.
GrridTest1.cs
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 14/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MbUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
namespace SmapleProject
{
[Parallelizable]
[TestFixture]
public class GridTest1
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
[SetUp]
public void SetupTest()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.InternetExplorer();
capabilities.SetCapability(CapabilityType.BrowserName, "iexplore");
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.SetCapability(CapabilityType.Version, "9.0");
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities);
baseURL = "https://www.google.co.in/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
driver.Quit();
}
[Test]
public void GoogleTest()
{
driver.Navigate().GoToUrl(baseURL + "/");
driver.FindElement(By.Id("gbqfq")).Clear();
driver.FindElement(By.Id("gbqfq")).SendKeys("Testing");
driver.FindElement(By.Id("gbqfb")).Click();
}
}
}
GridTest2.cs
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MbUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
namespace SmapleProject
{
[Parallelizable]
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 15/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
[TestFixture]
public class GridTest2
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
[SetUp]
public void SetupTest()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.BrowserName, "firefox");
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.SetCapability(CapabilityType.Version, "15.0");
Launch Grid
1. Run below command in on your console to launch Grid hub console:
2. Open two console and run below command to launch and register node with Grid hub.
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5555 -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5556 -role webdriver -hub
http://192.168.1.22:4444/grid/register -browser browserName=iexplore,platform=WINDOWS
Test Execution:
1. Build webdriver project.
2. Open Gallio Icarus console add created Webdriver project dll file.
http://3.bp.blogspot.com/-
CSCpTzyaUlw/UVLsIqTSpeI/AAAAAAAAAJE/SVjtqNEo5gA/s320/CSharpGrid2.jpg
3. Select both test script and click on run button. You should see both test case executed parallels.
http://3.bp.blogspot.com/-qH_UnHv1OXQ/UVLrayUnjXI/AAAAAAAAAI8/60Mdf6YunwE/s320/Grid2.jpg
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 16/17
05/01/2023 20:11 Selenium Test Automation: selenium que $ans -2
No comments:
Post a Comment
To leave a comment, click the button below to sign in with Blogger.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-2.html 17/17
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
Plus
Ramesh Kudikala
Selenium que $ans -3
View my complete profile
Steps to Handle Drag and Drop through Selenium Web Driver What are the challenges of Selenium Au
Selenium Webdriver interview Question
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch and create WebElement object for the DESTINATION element.
6.Perform ACTION
1.Click and Hold the source WebElement
2.Move to destination WebElement
3.Release the Element.
Example
Steps to make Single Select in Drop down through Selenium Web Driver.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 1/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
Example
Iterator it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());
while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango")){
System.out.println(el.getAttribute("value"));
el.click();
}
}
------------------------------------------------------------------------------------------------------------------------------
4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)
Steps to make Single Select in Drop down through Selenium Web Driver.
Example
Example
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 2/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)
Example
Example
driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Example
Example
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 3/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List frms= driver.findElements(By.tagName("iframe"));
System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();
------------------------------------------------------------------------------------------------------------------------------
When Browser opens in a new window or in a new tab, Web Driver cannot shift the control to the new
Window/ Tab. We need to collect the window handles in a page. Whenever a new window opens we need to
iterate and shift to the latest window handle.
TABS/New Window - 1
Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}------------------------------------------------------------------------------------------------------------------------------
TABS/New Window - 2
When two browsers are opened and Web Driver need to shift the control from Parent Window to Child
Window.
Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
TABS/New Window - 3
When second browser is closed/you close it and Web Driver need to shift the control from Child Window to
Parent Window.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 4/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
------------------------------------------------------------------------------------------------------------------------------
11. CALENDAR popups
Calendar PopUp - 1
/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='October
2012']]]]/descendant::a[text()='5']")).click();
------------------------------------------------------------------------------------------------------------------------------
In a Calender if we want to click on future month which is not currently displayed, we need to click on next
link until we get the required month.
This can be done by writing Customized wait. Check for particular date element in each month, if
not found move to next month.
/*makemytrip calendar*/
driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag){
try {
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group') and
descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future date
if(el !=null) //Check if the required date element is found or not
{
el.click(); // if required Date is found, then click the date
flag=false;
}
}
catch (Exception e) { //Catches exception if no element found
try {
Thread.sleep(500);
driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------------------------
In order to click on an menu item, first we need to move the mouse over Parent menu, later we can click
on any of the Menu child item.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 5/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
------------------------------------------------------------------------------------------------------------------------------
Example
act.contextClick(parentMenu).build().perform(); //Context Click
act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();
------------------------------------------------------------------------------------------------------------------------------
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 6/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
2. Go to the URL.
3. Fetch elements with tag //a in the entire page, store it in a List.
4. Get the count of Links present in the Page.
5. Loop through the links and print the Attributes
List allLinks= driver.findElements(By.xpath("//a"));
//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;i
{
//display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();
------------------------------------------------------------------------------------------------------------------------------
System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");
1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create an Web Driver Object.
3. Open an URL
System.setProperty("webdriver.chrome.driver", "D:\\sel\\browserdrivers\\Chromedriver.exe");
1. Import Selenium.Proxy
2. Create a Profile object for Firefox
3. Create a string variable with value.
4. Create a Proxy object.
5. Set the values through proxy.
6. Set the proxy preference to proxy object using profile object.
7. Pass the profile object to Firefox Driver.
import org.openqa.Selenium.Proxy
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 7/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);
------------------------------------------------------------------------------------------------------------------------------
WinWaitActive("Authentication Required")
Send("admin")
Send("{TAB} admin{TAB} {ENTER}")
------------------------------------------------------------------------------------------------------------------------------
8.Save the file as default save.(Authentication1.exe)
9.RUN/Compile the SCRIPT, it creates an exe.
10.Mention the exe path in the Program before creation of Driver.
EXAMPLE:
------------------------------------------------------------------------------------------------------------------------------
After coding the above mentioned steps, now start the driver and click on Download button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.
------------------------------------------------------------------------------------------------------------------------------
21. File Upload
Please follow the steps mentioned below.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 8/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable.
5. Fetch the upload button and click
4. Create new class:
Sikuli Script is packed in a JAR file - sikuli-script.jar. Depending on the operating system you use, you can
find the sikuli-script.jar in according places.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 9/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
7. After configuring in build path, create and initialize an instance of Screen object.
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
@Test
public void functionName() throws FindFailed {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
import org.junit.Test;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
@Test
public void functionName() throws FindFailed {
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 10/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3
//Close firefox
firefox.close();
}
}
No comments:
Post a Comment
To leave a comment, click the button below to sign in with Blogger.
seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 11/11
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Plus C
Ramesh Kudikala
Selenium ques $ans -4
View my complete profile
http://selenium-suresh.blogspot.in/2014/07/webdriver-interview-questions-and.html
Blog Archive
Selenium IDE
▼
▼ 2015 (15)
▼
▼ April (15)
Selenium IDE - Interview Questions
Selenium Quiz - 3
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 1/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
1. Right click on the command in Selenium IDE and select "Set / Clear Start Point"
2. Select the command in Selenium IDE and press "S" key on the keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other command as start point. Then the first start point will be removed
and the new start point will be set
9. How to insert a comment in Selenium IDE?Comments in Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>
10. How to insert a break point in Selenium IDE?Break point can be set in two ways in Selenium IDE
1. Right click on the command in Selenium IDE and select "Toggle Break Point"
2. Select the command in Selenium IDE and press "B" key on the keyboard
3. If you want to clear the break point once again Spress "B" key on the keyboard
4. You can set multiple break points in Selenium IDE
11. How to debug the tests in Selenium IDE?To debug or execute the test cases line by line. Follow the below mentioned steps
1. Insert a break From the location where you want to execute step by step
2. Run the test case
3. Execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time
12. How to export the tests from Selenium IDE to Selenium RC in different languages?From selenium IDE the test cases can be
exported into the languages
1. .Net
2. Java
3. Perl
4. Python
5. PHP
6. Ruby
The below mentioned steps can explain how to export the test cases
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As
13. How to export Selenium IDE Test Suite to Selenium RC Suites?From selenium IDE the test suites can be exported into the
languages as mentioned below
1. .Net
2. Java
3. Perl
4. Python
5. PHP
6. Ruby
The below mentioned steps can explain how to export the test suites
1. Open the test case from Selenium IDE
2. Select File -> Export Test Suite As
14. Which is the command used for displaying the values of a variable into the output console or log?The command used for
displaying the values of a variable into the output console or log - echo
If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo "The sample message"
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
Note: Here var1 is the variable
15. Which are the browsers supported by Selenium RC?Supported browsers for Selenium RC include:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 2/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
16. Which are the Operating Systems supported by Selenium?
Selenium IDE
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
17. What is Selenium RC?Selenium-RC is the solution for tests that need a little more than just simple browser actions and a linear
execution. Selenium-RC leverages the full power of programming languages, creating tests that can do things like read and write
external files, make queries to a database, send emails with test reports, and practically anything else a user can do with a normal
application.
You will want to use Selenium-RC whenever your test requires logic not supported by running a script from Selenium-IDE
18. Why Selenium RC is used?Selenium-IDE does not directly support:
1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
The reason behind why Selenium-IDE does not support the above mentioned requirements is IDE supports only HTML language.
Using HTML language we cannot achieve the above mentioned requirements. Because HTML does not support conditional, looping
and external source connectives.
To overcome the above mentioned problems Selenium RC is used.
Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP, and Ruby. In these languages we can write the programme to
achieve the IDE issues
19. Which are the languages supported by Selenium RC?The languages supported by Selenium RC
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby
20. What is Selenium Grid?Selenium Grid is part of Selenium suite of projects. Selenium Grid transparently distribute your tests on
multiple machines so that you can run your tests in parallel, cutting down the time required for running in-browser test suites. This
will dramatically speeds up in-browser web testing, giving you quick and accurate feedback you can rely on to improve your web
application.
21. What is Selenium WebDriver or Google WebDriver or Selenium 2.0?WebDriver uses a different underlying framework from
Selenium’s javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC.
WebDriver does not depend on a javascript core embedded within the browser, therefore it is able to avoid some long-running
Selenium limitations.
WebDriver’s goal is to provide an API that establishes
• A well-designed standard programming interface for web-app testing.
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The
developers of Selenium and of WebDriver felt they could make significant gains for the Open Source test automation community be
combining forces and merging their ideas and technologies. Integrating WebDriver into Selenium is the current result of those efforts.
22. What are the capabilities of Selenium WebDriver or Google WebDriver or Selenium 2.0?One should use WebDriver when
requiring improved support for
• Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
• Handling multiple frames, multiple browser windows, popups, and alerts.
• Page navigation.
• Drag-and-drop.
• AJAX-based UI elements.
23. What is the architecture of Selenium RC?The Selenium Server which launches and kills browsers, and acts as an HTTP proxy for
browser requests.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 3/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Client libraries for various programming languages, each of which instructs the Selenium Server in how to test the AUT by passing it
your test script’s Selenium commands.
The diagram shows the client libraries communicate with the Server passing each Selenium command for execution. Then the server
passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript
interpreter, executes the Selenium command, which effectively, runs the check you specified in your Selenese test script.
24. What is the architecture of Selenium Grid?
The below mentioned theory explains about the setup of Selenium Grid with architecture and how it works.Selenium Grid builds on
the traditional Selenium setup, taking advantage of the following properties:
* The Selenium test, the application under test, and the remote control/browser pair do not have to be co-located. They communicate
through HTTP, so they can all live on different machines.
* The Selenium tests and the web application under test are obviously specific to a particular project. Nevertheless, neither the
Selenium remote control nor the browser is tied to a specific application. As a matter of fact, they provide a capacity that can easily
be shared by multiple applications and multiple projects.
Consequently, if only we could build a distributed grid of Selenium Remote Controls, we could easily share it across builds,
applications, projects - even potentially across organizations. Of course we would also need to address the scalability issues as
described earlier when covering the traditional Selenium setup. This is why we need a component in charge of:
* Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
Selenium Grid calls this component the Selenium Hub.
* The Hub exposes an external interface that is exactly the same as the one of a traditional Remote Control. This means that a test
suite can transparently target a regular Remote Control or a Selenium Hub with no code change. It just needs to target a different IP
address. This is important as it shields the tests from the grid infrastructure (which you can scale transparently). This also makes
the developer’s life easier. The same test can be run locally on a developer machine, or run on a heavy duty distributed grid as
part of a build – without ever changing a line of code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is also in charge of routing the Selenese requests from the tests
to the appropriate Remote Control as well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is no available Remote Control in the grid providing the
appropriate capabilities. As soon as a suitable Remote Control becomes available, the Hub will serve the request. For the whole time,
the tests do not have to be aware of what is happening within the grid; it is just waiting for an HTTP response to come back.
25. Does Selenium support mobile internet testing?Selenium supports Opera. And opera is used in most of the Smart phones. So
whichever Smart phone supports opera, selenium can be used to test. So, one can use Selenium RC to run the tests on mobiles.
26. Does Selenium support Google Android Operating System?Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0
supports Android Operating System. There are several libraries written to support Android Operating System.
27. What are the types of text patterns available in Selenium?There are three types of patterns available in Selenium
1. globbing
2. regular expressions
3. exact
28. How to use regular expressions in Selenium?Regular expressions in Selenium IDE can be used with the keyword - regexp: as a
prefix to the value and patterns needs to be included for the expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each time you run the test case. So this can be written with a
regular expression as mentioned below
Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}
29. What are the regular expression patterns available in Selenium?Selenium regular expression patterns offer the same wide array of
special characters that exist in JavaScript. Below are a subset of those special characters
PATTER
MATCH
N
. any single character
[] character class: any single character that appears inside the brackets
* quantifier: 0 or more of the preceding character (or group)
+ quantifier: 1 or more of the preceding character (or group)
? quantifier: 0 or 1 of the preceding character (or group)
{1,5} quantifier: 1 through 5 of the preceding character (or group)
| alternation: the character/group on the left or the character/group on the right
() grouping: often used with alternation and/or quantifier
30. What is Selenese?Selenium set of commands which are used for running the test are called asSelenese.
There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable
31. How do you add check points or verification points in Selenium?check points or verification points are known as Assertions in
Selenium. The keywords with below mentioned prefix will be used for adding check points or verification points.
1. verify
2. assert
3. waitFor
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 4/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
32. What is Assertion in Selenium?Assertion is nothing but a check or verification point.
Assertion verifies the state of the application conforms to what is expected.
Examples include “make sure the page title is X†and “verify that this checkbox is checked.
33. What are the types of Assertions there in Selenium?Selenium Assertions can be used in 3 modes:
1) assert - When an assert fails, the test will be aborted. If you are executing test suite, the next state case will start
2) verify - When a verify fails, the test will continue execution, logging the failure.
3) waitFor - waitFor commands wait for some condition to become true (which can be useful for testing Ajax applications). They will
succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true
within the current timeout setting
34. When to use Assert, Verify and WaitFor in Selenium?1) assert - If the expected value is mandatory to continue with the next set of
steps we will use Assert. As Assert aborts the test, if the expected value doesn't match. It is good to use for any mandatory checks.
2) verify - If the expected value is optional to continue with the next set of steps we will use Verify. As Verify continues executing
with the next set of steps, if the expected value doesn't match. It is good to use for any optional checks.
3) waitFor - If your test needs to wait, if the expected value is not matching we use waitFor. We normally use waitFor for AJAX kind of
controls loading within a page
35. What is an Accessor in Selenium?Accessor is one of the type of Selenese.
I. Accessors are used for storing the value of a target in a variable.
Ex:
1) storeTitle - Stores the title of a window in a variable
2) storeText - Stores the target element text in a variable
II. Accessors are also used for evaluating the result and storing the result in a variable
Ex: storeTextPresent - Evaluates whether the text is present in the current window. If the text is present stores true in the variable else
stores false
Ex: storeEementPresent - Evaluates whether the element is present in the current window. If the element is present stores true in the
variable else stores false
36. When to use Accessors in Selenium?Accessors are mostly used for storing the value in a variable.
The variable can be used for following reasons:
1) To get the value from an element and comparing with some dynamic value
2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3 and step4
3) To execute some statements in a loop based on the value returned by the element
37. How to capture bitmaps in Selenium?Bitmaps are captured using the Selenium set of commands. There are two modes of
capturing the bitmaps
1) Capture the bitmap for the entire page - it captures the browser main page area of AUT
2) Capture the bitmap for the screen shots - it captures the entire screen shot like the print scree that you give from your keyboard
Selenium doesn't support bitmap capturing for an element on AUT.
38. Which are the commands used for capturing the bitmaps?
captureEntirePageScreenshot
captureEntirePageScreenshotAndWait
Note:
39. What is the difference between captureEntirePageScreenshot and CaptureScreenShot?captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other argument is back ground color
CaptureScreenShot
1. This captures the System screen shot
2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.
40. How do you set user extensions in Selenium IDE?1. Open user-extensions.js with an editor (Notepad, etc.); it's found in the
selenium\core\scripts folder. If it doesn't exist, just create it.
2. If you need to, commit the user-extensions.js file (like if you use subversion).
3. Open Selenium IDE and choose the Options menu and then Options... from that menu.
4. Make sure the path to your user-extensions.js file is entered in the Selenium Core extensions field (like
\selenium\core\scripts\user-extensions.js)
5. Press OK button on options
6. Restart the IDE to reflect your extensions.
Note:
41. What are the limitations of Selenium IDEThe limitations of Selenium IDE are:
1) Selenium IDE uses only HTML language
2) Conditional or branching statements execution like using of if, select statements is not possible
3) Looping statements using is not possible directly in Selenium HTML language in ide
4) Reading from external files like .txt, .xls is not possible
5) Reading from the external databases is not possible with ide
6) Exceptional handling is not there
7) A neat formatted Reporting is not possible with ide
To eliminate the above issues we use Selenium RCAfter reopen, Selenium IDE may show compilations errors if the user-extensions.js
file has any syntax errors. This command runs with only mozilla firefox when you run the tests from RC. Other browsers it will not
support
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which
captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC
only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie"
utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshotAndWait for details.
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which
captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 5/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie"
utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please
seecaptureEntirePageScreenshot for more details
Used for running tests
Operating Systems Supported:
Used for starting browser and run tests
Operating Systems Supported:
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
earlier versions of Mozilla Firefox 2.x
Mozilla Firefox 4.x
Selenium is a suite of tools for web automation testing. Selenium first came to life in 2004 when Jason Huggins was testing an
internal application at Thought Works. Selenium was a tremendous tool, it wasn’t without its drawbacks. Because of its
JavaScript based automation engine and the security limitations browsers apply to JavaScript, different things became impossible to
do.
Selenium Suite of projects includes:
Selenium IDE
Selenium Core
Selenium 1 (known as Selenium RC or Remote Control)
Selenium 2 (known as Selenium Web driver)
Selenium-Grid
Selenium RC
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 6/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
3. If there is any dependency between the test cases, it is very difficult to execute
4. Running the test suites in junit will be helpful for only independent test cases.
Note: The dependent test case related issues can be addressed by using TestNG with junit
9. What are the advantages of using TestNG over Junit?The advantages of using TestNG over Junit:
1. The challenges of junit can be addressed using TestNG read What are the challenges with Selenium RC test suites when running in
JUnit? for more details
2. You can execute the test cases dependent with each other read Runnning Selenium RC Tests Sequentially using TestNG for more
details
3. You can execute test cases in a group read Use Group in TestNG framework for more details
4. You can generate the reports using TestNg
10. What are the basic annotations used to run TestNG tests in Selenium?The basic annotations used to run TestNG tests in Selenium
RC:
1. @BeforeClass: The annotated method with @BeforeClass will be run before the first test method in the current class is invoked.
2. @AfterClass: The annotated method with @AfterClass will be run after all the test methods in the current class have been run.
3. @BeforeMethod: The annotated method with @BeforeMethod will be run before each test method.
4. @AfterMethod: The annotated method with @AfterMethod will be run after each test method.
5. @Test: Marks a class or a method @Test with as part of the test.
11. How to run test cases with dependent in Selenium using TestNG?The @Test should be followed by (dependsOnMethods =
"testLogin")
Note:- The test case will be executed after the testLogin case
Ex: @Test(dependsOnMethods = "testLogin")
12. How to run the test cases in group in Selenium using TestNG?Test cases in group in Selenium using TestNG will be executed with
the below options.
If you want to execute the test cases based on one of the group like regressiontest or smoketest
@Test(groups = {"regressiontest", "smoketest"})
13. How to execute the test cases in an XML format using TestNG in Selenium?If you want to execute a java file MercTestNgSuite.java
which is there in the package com.src.testng. You can use the below mentioned code in a xml file. And the test can be run by right
clicking the XML and running as TestNG Suite
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false"
annotations="JDK">
<test verbose="2" name="com.src.testng.MercTestNgSuite" junit="false" annotations="JDK">
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
</classes>
</test>
</suite> ??
14. How to incude or exclude the selenium rc test cases using xml in TestNG?Including or excluding of selenium rc test cases using
xml in TestNG can be done using the keywords include or exlude
For including a test case we need to use <include name="method name"/> under the class whichever the method you want to include
For excluding a test case we need to use <exclude name="method name"/> under the class whichever the method you want to include
For example if you have a class MercTestNgSuite in package com.src.testng want to include the methods like:
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
5. testVerifyFlightConf
and exclude
6. testLogout
the xml can be written as mentioned below.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false"
annotations="JDK">
<test verbose="2" name="com.src.testng.MercTestNgSuite" junit="false" annotations="JDK">
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
<include name="testVerifyFlightConf"/>
<exclude name="testLogout"/>
</methods>
</classes>
</test>
15. How to execute the selenium test suite with testNG in XML?Assume that you have two classes which are having suite of test cases
with the below mentioned methods.
class1 or suite 1:
class1 or suite 2:
The two class suites can be executed as mentioned
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false"
annotations="JDK">
<test verbose="2" name="com.src.testng.*" junit="false" annotations="JDK">
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 7/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
</methods>
<class name="com.src.testng.MercTestNgSuite2"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
<include name="testVerifyFlightConf"/>
<include name="testLogout"/>
</methods>
</classes>
</test>
</suite>
16. How to run Selenium IDE test suite with user extensions using Selenium Remote Control?to run Selenium IDE test suite with user
extensions using Selenium Remote Control we need to use the below command.
java -jar selenium-server.jar -userExtensions user-extensions.js -htmlSuite "*<browser>" "<base URL>" "<Selenium test suite file>" "
<results log file>" -timeout <millise>
17. How to start selenium rc server with user extensions?The command used is
java -jar selenium-server.jar -userExtensions user-extensions.js
Note: In this case, the java script file user-extensions.js file name should always fixed. If the name or extension is changed the
selenium rc server will not start.
18. What are the limitations of selenium RCThe limitations of selenium RC are:
1) Switching between the multiple instances of the same browser is not possible
2) Switching between the multiple instances of the different browsers is not possible
3) Browser navigation, like back and forward button emulations is not possible
4) Limited features in terms of drag and drop of objects
5) To work with Ajax based UI elements there are very limited features are there with Selenium RC
To overcome the above limitations we use selenium web driver or google web driver
19. How to do database testing using selenium rc?There are no selenium specific commands to do the database testing. But, you have
the work around with native language. Here is the example how you can make database testing in selenium. The below mentioned
commands will help you to begin with.
Before you use the below code You should have created the DSN name for MS SQL Server DB or Oracle DB using ODBC drivers. Here
the name that we have used for the database DSN name is QT_Flight32. And the table in that database we are using is Orders. Hope
the remaining steps you can easily understand.
//KEEP THE NAME OF THE PACKAGE
//IMPORT THE SQL PACKAGE
//DECLARE THE CLASS
//WRITE THE MAIN METHOD TO CONNECT TO THE DATABASE
try{
// LOAD THE DATABASE DRIVER
// ESTABLISH THE CONNECTION TO THE DATABASE
// GET A STATEMENT FOR THE CONNECTION
// PREPARE THE SQL STATEMENT
// EXECUTE THE SQL QUERY AND STORE IN RESULTS SET
// LOOP THE RESULT TILL IT REACHED END
// CLOSE THE RESULT, STATEMENT AND CONNECTION
}
// HANDLE THE SQL EXCEPTION
catch( SQLException se ) {
System.out.println( "SQL Exception:" ) ;
// PRINT TILL ALL THE ECEPTIONS ARE RAISED
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
}
//CATCH THE CLASS EXCEPTION
catch( Exception e ) {
System.out.println( e ) ;
}
}
}
while( se != null ) {
rs.close() ;
stmt.close() ;
conn.close() ;
// rs.getString(1) - FIRST COLUMN
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 8/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
// rs.getString(2) - SECOND COLUMN ETC
while( rs.next() )
System.out.println( rs.getString(1) + rs.getString(2)+ rs.getString(3)+ rs.getString(4)) ;
ResultSet rs = stmt.executeQuery( strSQL ) ;
String strSQL = "SELECT * FROM Orders";
Statement stmt = conn.createStatement() ;
Connection conn = DriverManager.getConnection( "jdbc:odbc:QT_Flight32" ) ;
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
public static void main( String args[] )
{
class JDBCODBCTestCase
{
import java.sql.* ;
package com.src.test;the class by name MercTestNgSuite2 in the package com.src.testng with the methods
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
5. testVerifyFlightConf
6. testLogout the class by name MercTestNgSuite in the package com.src.testng with the methods
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
1. takes a single argument in integer format
ex: thread.sleep(2000) - will wait for 2 seconds
2. Waits for only once at the command given at sleep.
1. takes a single argument in string format
ex: selenium.setSpeed("2000") - will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in setSpeed.
1: What is Selenium 2.0? I have heard this buzz word many times.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 9/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The
developers of Selenium and of WebDriver felt they could make significant gains for the Open Source test automation community be
combining forces and merging their ideas and technologies. Integrating WebDriver into Selenium is the current result of those efforts.
8.When to Use WebDriver?
One should use WebDriver when requiring improved support for
* Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
* Handling multiple frames, multiple browser windows, popups, and alerts.
* Page navigation.
* Drag-and-drop.
* AJAX-based UI elements.
Advantages of web driver compared to selenium.
1) Support for iPhone and Android testing
2) Implementation of listeners - a much awaited feature
3) Better features for Ajax testing.
4) You can easily simulate clicking on front and back button of browser.
5) You can extract objects in bulk like QTP. For ex - extract all links of page. With RC this was a big hastle
6) Unlike RC you don’t have to start a server in webdriver.
7) You can simulate movement of a mouse using selenium.
8) Tabs and pops are more or less the same. RC can also handle and Webdriver can also handle.
9) You can find coordinates of any object using Webdriver.
10) You have classes in Webdriver which help you to simulate key press events of keyboard.
10) Keyword driven framework is very easy to build in webdriver.
9.Which browsers does WebDriver support?
The existing drivers are the ChromeDriver, InternetExplorerDriver, FirefoxDriver, OperaDriver and HtmlUnitDriver. For more
information about each of these, including their relative strengths and weaknesses, please follow the links to the relevant pages.
There is also support for mobile testing via the AndroidDriver and IPhoneDriver.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 10/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
content.Firefox extension that integrates both with the browser and its DOMInspector. Thus, is't very lightweight and cross-platform.
It is valuable mainly as a web/XML-app development and hacking tool.XPath Checker XPather
String-match Patterns
Feature rich XPath generator, editor, inspector and simple extraction tool...
5 what is diff b/w Firefox and chrome and ie?
Selenium scripts will run very fast in Firefox when we compare with the IE.
6 .how can u capture the entire pages, one page in single window? How it use I mean that cmd?
captureEntirePageScreenshot ( filename,kwargs )
· filename - the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be
created if they do not exist, and an exception will be thrown, possibly by native code.
· kwargs - a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid
options:
background
the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal
layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black
background is exposed (possibly obscuring black text).
7. How many types of pattern matching, list of it? Like regular expressions, group exp,exact expressions?
Various Pattern syntaxes are available for matching string values:
glob:
Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax
typically used in command-line shells. In a glob pattern, "*" represents any sequence of characters, and "?"
represents any single character. Glob patterns match against the entire string.
regexp:
Match a string using a regular-expression. The full power of JavaScript regular-expressions is available.
exact:
Match a string exactly, verbatim, without any of that fancy wildcard stuff.
If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern.
8 what is diff b/w wait for page to load, thread. Sleep, set speed?
Sleep, suspends the current thread for a period of time.
The expiration of that time is what will make the thread runnable.
Wait, suspends the current thread until some event has done.
9 what are the different startup modes in selenium RC
Mainly we had 2 types to startup modes in selenium RC.
you can launch Selenium Remote Control server using following command ( Make sure that you are into directory where selenium-
server.jar is located or this directory is in your path variable ) -
java -jar selenium-server.jar
This command should start Selenium Server on your machine and your automation scripts are ready to interact with your web
application using this server. You can leave this server up and running while you are developing and executing your automation
scripts. If you wish, you can also start Selenium Remote Control in interactive mode and start playing with its various commands on
command prompt itself. In order to do that, you need to supply a command line option called interactive.
java -jar selenium-server.jar -interactive
Apart from this there are many command line options that you can specify while starting selenium RC.
-port :
-timeout : an integer number of seconds before we should give up
-interactive:
-singleWindow:
-profilesLocation:
-forcedBrowserMode : sets the browser mode to a single argument (e.g. "*iexplore") for all sessions, no matter what is passed to
getNewBrowserSession
-forcedBrowserModeRestOfLine :
-userExtensions :
-browserSessionReuse:
-firefoxProfileTemplate <dir>:
-debug: puts you into debug mode, with more trace information and diagnostics on the console
-browserSideLog:
-ensureCleanSession:
-trustAllSSLCertificates:
-log :
-htmlSuite :
-proxyInjectionMode:
-dontInjectRegex :
-userJsInjection :
-userContentTransformation :
10 how to automate flash based application?
Both selenium RC and selenium Webdriver can be used for flash/flex application testing. Procedure is same for testing flash and flex
applications using selenium. FlashSelenium API in Selenium RC helps us to test flash/flex based applications using RC. While in
webdriver, you need to make your own custom Javascript Execution functions in order to test flash applications using Selenium. But
in order to test such appications, you need to make sure that you have the access to source code of the application. This means that
you cannot just go and test any flash application present on the internet.
To test flash application u need to add below flash jar file to the eclipse.
"Flashselenium-java-client-extension.jar"
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 11/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
While writing the code u need to import the flash lib
import com.thoughtworks.selenium.FlashSelenium;
a regular expression which is matched against all test HTML content; the second is a string which will replace matches. These flags
can be used any number of times. A example of how this could be useful: if you add "-userContentTransformation https http" then all
"https" strings in the HTML of the test application will be changed to be "http". specifies a JavaScript file which will then be injected
into all pagesan optional regular expression that proxy injection mode can use to know when to bypss injection puts you into proxy
injection mode, a mode where the selenium server acts as a proxy server for all content going to the test application. Under this
mode, multiple domains can be visited, and the following additional flags are supported: Run a single HTML Selenese (Selenium
Core) suite and then exit immediately, using the specified browser (e.g. "*firefox") on the specified URL (e.g.
http://www.google.com"). You need to specify the absolute path to the HTML test suite as well as the path to the HTML results file
we'll generate. writes lots of debug information out to a log file Forces the Selenium proxy to trust all SSL certificates. This doesn't
work in browsers that don't use the Selenium proxy. If the browser does not have user profiles, make sure every new session has no
artifacts from previous sessions. For example, enabling this option will cause all user cookies to be archived before launching IE,
and restored after IE is closed. enables logging on the browser side; logging messages will be transmitted to the server. This can
affect performance. normally, we generate a fresh empty Firefox profile every time we launch. You can specify a directory to make us
copy your profile directory instead. stops re-initialization and spawning of the browser between tests
-avoidProxy: By default, we proxy every browser request; set this flag to make the browser use our proxy only for URLs containing
'/selenium-server' indicates a JavaScript file that will be loaded into selenium sets the browser mode to all the remaining tokens on
the line (e.g. "*custom /some/random/place/iexplore.exe") for all sessions, no matter what is passed to
getNewBrowserSession Specifies the directory that holds the profiles that java clients can use to start up selenium. Currently
supported for Firefox only. puts you into a mode where the test web site executes in a frame. This mode should only be selected if the
application under test does not use frames.puts you into interactive mode. See the tutorial for more details the port number the
selenium server should use (default 4444) stringregexp pattern
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which
captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC
only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie"
utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see
http://www.screengrab.org and http://snapsie.sourceforge.net/ for details.
Arguments:
An interactive editor for XPath expressions
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 12/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
selenium.open("http://www.google.com/");
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
{ //Read data from excel sheet
selenium.type("name=q",s.getCell(0,i).getContents());
selenium.click("btnG");
Thread.sleep(1000); } }
@AfterClass
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}
}
package test;
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
public class DefaultTNG {
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testDefaultTNG()throws Exception {
http://4.bp.blogspot.com/-yM2sYrVfXR0/UBDmC3NqLFI/AAAAAAAAAC0/SWELbdLlHeg/s320/LoginScenario.png
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 13/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testDefaultTNG()throws Exception {
FileInputStream fi=new FileInputStream("E:\\Selenium\\LoginExcel.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
selenium.open("http://127.0.0.1/orangehrm-2.6/login.php");
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
{
//Read data from excel sheet
String s1 = s.getCell(0,i).getContents();
String s2 = s.getCell(1,i).getContents();
selenium.type("txtUserName",s1);
selenium.type("txtPassword",s2);
selenium.click("Submit");
Thread.sleep(2000);
selenium.click("Link=Logout");
}
}
@AfterClass
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}
After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel sheet....
Below is the sample script to write results to excel sheet...
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 14/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
@Test
public void testImportexport1() throws Exception {
// Read data from excel sheet
FileInputStream fi = new FileInputStream(
"F:\\Framework\\testdata\\Login1_Credentials.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
String a[][] = new String[s.getRows()][s.getColumns()];
// Write the input data into another excel file
FileOutputStream fo = new FileOutputStream(
"F:\\Framework\\Results\\LoginResult1.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("loginresult1", 0);
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
System.out.println("s.getRows() = " + s.getRows());
for (int i = 0; i < s.getRows(); i++) {
System.out.println("s.getColumns = " + s.getColumns());
for (int j = 0; j < s.getColumns(); j++) {
a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label l1 = new Label(2, 0, "Result");
ws.addCell(l);
ws.addCell(l1);
}
}
for (int i = 1; i < s.getRows(); i++) {
selenium.type("Email", s.getCell(0, i).getContents());
selenium.type("Passwd", s.getCell(1, i).getContents());
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");
System.out.println("the value of aa is::" + aa);
if (aa)
{
Label l3 = new Label(2, i, "fail");
ws.addCell(l3);
System.out.println("Login Failure");
Thread.sleep(10000);
} else {
Label l2 = new Label(2, i, "pass");
ws.addCell(l2);
selenium.click("link=Sign out");
Thread.sleep(10000);
}
}
wwb.write();
wwb.close();
}
@AfterClass
public void tearDown() throws Exception {
selenium.stop();
seleniumserver.stop();
}
}
Your input data should be like this....
http://4.bp.blogspot.com/-3Ff4BSZN7D0/UBeSMX9qgxI/AAAAAAAAADQ/uFDLwqm6pa0/s320/Login1_Credentials.png
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 15/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Type in the name "TestDB" (no quotes, but leave the cases the same) for the Data Source Name
Click CREATE and select a file to save the database to (I chose "d:\java\TestDB.mdb") - this creates a new blank MS Access database!
Click "ok" all the way out Now our data source is done!
Here's a complete program showing how to access your new DSN data source:
package qtt.selenium;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import com.thoughtworks.*;
import com.thoughtworks.selenium.DefaultSelenium;
import org.junit.*;
import org.openqa.selenium.server.SeleniumServer;
public class DBtest
{
DefaultSelenium selenium;
SeleniumServer server;
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:TestDB";
String username = "";
String password = "";
@Before
public void setup()throws Exception
{
server = new SeleniumServer();
server.start();
selenium = new DefaultSelenium("127.0.0.1",4444,"*chrome","http://");
selenium.start();
}
@Test
public void test()throws Exception
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
Statement st = conn.createStatement();
// st.executeUpdate("drop table survey;");
st.executeUpdate("create table suresh(id int,name varchar(30),Homesite varchar(30));");
st.executeUpdate("insert into suresh (id,name,Homesite) values (1,'SURESH','selenium-suresh.blogspot.com')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM suresh");
if(rs.next());
{
String homesite = rs.getString(3);
selenium.open(homesite);
selenium.windowMaximize();
Thread.sleep(30000);
}
}
@After
public void teardown() throws Exception
{
selenium.stop();
server.stop();
}
}
There are some scenarios where we need to run multiple test cases. Either we can run those test cases independently or together. But
there are some real time cases where we need to run our test cases in a particular order. In this case we would prefer Test Suite to
combine the test cases together and decide their orders and run those.
Below are the steps
1. Create a Test Suite class where we create the Test Suites which will call all the test cases in a particular order.
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class TestSuite1 extends TestCase {
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite( TestCase1.class);
suite.addTestSuite( TestCase2.class);
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 16/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
suite.addTestSuite( TestCase3.class);
return suite;
}
public static void main(String arg[])
{
TestRunner.run(suite());
}
}
Step 2. Create your first test case
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase1 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Suresh");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj"));
}
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
}
}
Step 3. Create your second test case
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase2 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Suresh Babu");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Suresh Babu"));
}
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
}
}
Step 4. Create your third test case
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase3 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 17/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "http:/selenium-suresh.blogspot.com");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("http://selenium-suresh.blogspot.com"));
}
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
}
Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically. Each time id gets
generated differently. So to handle this situation we use some JavaScript functions.
starts-with
if your dynamic element's ids have the format where button id="continue-12345" where 12345 is a dynamic number you could use
the following
XPath: //button[starts-with(@id, 'continue-')]
contains
Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having to couple it with the ‘top’ and ‘business’
classes using the following
XPath: //input[contains(@class, 'suggest')].
Automation using selenium is a great experience. It provides many way to identif an object or element on the web page.
But sometime we face the problems of idenfying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple checkboxes with same name and same id. More than one button
having
same name and ids. There are no way to distingues those element. In this case we have problem to instruct selenium to identify a
perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same type and same name.
It is really tough to select third or fifth.
input type='checkbox' name='chk' first
input type='checkbox' name='chk' second
input type='checkbox' name='chk' third
input type='checkbox' name='chk' forth
input type='checkbox' name='chk' fifth
input type='checkbox' name='chk' sixth
Thare are some function we can use in Xpath to identify the abject in above cases. An XPath expression can return one of four basic
XPath data types:
* String
* Number
* Boolean
* Node-set
XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-
space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()
I will show you how we can use some of these above functions in xpath to identify the objects.
Node Set : last()
In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last object among all similar
objects.
Below code will check or uncheck the last checkbox.
selenium.click("xpath=(//input[@type='checkbox'])[last()]");
How we can select the second last checkbox and third last checkbox. We can use last()- function to indentify the last object among all
similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.
selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");
Node Set : position()
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 18/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command
selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");
above code will select second and forth checkbox respectively.
String : starts-with()
Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.
XPath: //button[starts-with(@id, 'continue-')]
Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having
to couple it with the ‘top’ and ‘business’ classes using the following
XPath: //input[contains(@class, 'suggest')].
package com.test.webdriver;
import static org.testng.AssertJUnit.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Driver {
private WebDriver driver;
@BeforeClass
public void Startup(){
driver = new FirefoxDriver();
}
@Test (description="Google Login")
public void GoogleLogin() throws Exception{
driver.get("http://www.gmail.com");
assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
driver.findElement(By.id("Email")).sendKeys("*********");
driver.findElement(By.id("Passwd")).sendKeys("**********");
driver.findElement(By.id("signIn")).click();
Thread.sleep(10000);
driver.switchTo().frame("canvas_frame");
driver.findElement(By.id("gbgs4dn")).click();
driver.findElement(By.id("gb_71")).click();
driver.switchTo().defaultContent();
assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
}
@AfterClass
public void teardown(){
driver.quit();
}
}
1.Check that Java is installed in your system by using the command “java -version”. If Java is installed it will give the output about
Java Version that is installed in your system. Else download the Java from Java website
(http://www.java.com/en/download/index.jsp).
2.Check ANT is installed in your system by using the command “ant -version”.If Ant is installed it will give the output about Ant
Version that is installed in your system. Else download the Apache Ant from Apache website (http://ant.apache.org/).
3.Download Selenium Grid from Selenium Grid website(http://selenium-grid.seleniumhq.org/download.html) and unpack it.
4.Go to the Unpacked directory of the Selenium grid using command prompt and type the command “ant launch-hub”. This will
launch the Selenium Grid Hub on a default port “4444” to check whether the selenium grid is running. Type the
URL http://localhost:4444/console on your browser and check that you are able to see the selenium hub console on the browser.
5.Now go to the same Selenium Grid directory using command prompt and type the command “ant launch-remote-control”. This will
start the Selenium Grid Remote control on default port “5555” and environment “*firefox” and register it to the Hub which you had
earlier started.
6. Now after starting the selenium remote control we will test the example provided with Selenium Grid for sequence testing in single
machine. For this go to the Selnium grid folder from command prompt and type the command “ant run-in-demo-sequence”. This will
execute the test example provided with selenium grid to be executed in sequence.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 19/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Now you may had noticed in the setting up steps that I am running the test in sequence. You may think in your mind that, what's
special in that? The same things can be achieved when we use a Selenium RC.Then here comes the important part of Selenium Grid.
1. Start the hub and one remote control in the same way as in the earlier setting up steps.
2. Now go to the Selenium Grid folder using command prompt and type the command
This will start another remote control on port “5556” and register it to the local hub. If you want to register more remote control to
the Hub. You can do that by starting multiple remote control but with different ports.
3. To know the no. of registered remote control onto a hub go to the URL http://localhost:4444/console. It will give you a view as
follows:
http://3.bp.blogspot.com/-1XBMOYO2Cto/UGVMv0Q24oI/AAAAAAAAAD8/xaU3x3I9OzU/s1600/HostNames.png
4.Now to run the test in parallel. Go to the selenium grid directory using command prompt and type the command “ant run-demo-in-
parallel”. This will run the example tests given with selenium grid in parallel.
In this case start the Hub normally as you do in any of the system.
ant -Dport= -Dhost= -DhubURL= -Denvironment= launch-remote-control
Here
“-Dport” should be used to set the port of the remote control.
“-Dhost” should be used to set the host(where the remote control has been started) IP. This is the IP which the hub will use to talk to
the remote control.
“-DhubURL” should be used to set the Hub Url where the current remote control will register itself.
“-Denvironment” should be used to set an environment name that remote control represents to the hub.
Now start 4 different remote controls from 2 different machines and register them to the hub.
After this check the Hub console. It will look similar to the table as shown below depending upon the remote control that are
registered to the Hub.
http://1.bp.blogspot.com/-GzE3Q0yWFmc/UGVNUZvazfI/AAAAAAAAAEE/jjSMI5EGTYo/s320/Host.png
Then to verify your set-up go to the Selenium Grid folder from the command prompt and type the command “ant run-demo-in-
parallel”
This will run an example test accompanied with the Selenium Grid to run in parallel.
1. Remote Execution of the selenium tests can be done using Selenium Grid without actually copying your test code to to remote
system.
2. Selenium Grid can be used to save time by executing independent testcases in parallel.
3. Load Testing can be done if we register a lot of remote control to a single hub and execute testcase in parallel to simulate multiple
transactions at a single timeperiod.
Automation Frameworks
1. What is Test Automation Framework?
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 20/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Suppose you are given a task where you have to automate some test cases for an application. When you are finished automating the
application, what would be your expectations from the scripts you have created? Wouldn’t you want that –
All the above points can be achieved by using a proper Automation Framework.
An Automation Framework is a set of guidelines that you can follow during test case scripting to achieve the above mentioned
results. This set of guidelines can be anything such as –
Specifying the folder structure that will be used for storing test cases, function libraries, object repositories and data sheets.ü
Deciding the format of the data sheets i.e., how the data sheets would be grouped and how the scripts will access these data sheets.ü
Following proper coding standards and using comments so that the code can be understood easily by anyone.ü
Using reusable functions wherever possible so that lesser amount of rework is needed in case of any changesü
Following the guidelines (that you have set) consistently during the creation of the test scripts would result in the creation of an end
product(your Automation Framework) that include all the features which you had targeted for.
http://1.bp.blogspot.com/-Oqy-_1xY4Tk/UKTItYJDnlI/AAAAAAAAAEU/Mhz0bLDyUQo/s320/AutomationFramework.png
Types of Frameworks
1.Keyword framework
2.Datadriven framework
3.Modular framework
4.Hybrid framework.
1.Keyword framework
In Keyword Driven framework, you can create various keywords and associate a different action or function with each of these
keywords. Then you create a Function Library that contains the logic to read the keywords and call the associated action.
Advantages of Keyword Driven Framework
The keyword and function libraries are completely generic and thus can be reused easily for different applications.ü
All the complexity is added in the function libraries. Once the libraries are ready, it becomes very easy to write the actual test script
steps in excel sheets.ü
Disadvantages of Keyword Driven Framework
Lot of time and effort needs to be spent initially to create the function libraries. The benefits of the keyword driven framework are
realized only after it has been used for longer periods of time.ü
Very high programming skills are needed to create the complex keyword library functions.ü
It’s not easy for new people to understand the framework quickly.ü
2.Datadriven framework
In Data Driven Framework, the data is NOT hard-coded in the test scripts. Instead, it is stored in some external files. The test
script first connects to the external data source and then extracts the data from that source. Most of the times, excel sheets are used to
store the data. Other external data sources that are frequently used are –
Text files.ü
XML files.ü
Databases.ü
Combination of more than one external file.ü
Advantages of Data Driven Framework
Since the data is kept separate from the test script, the same script can be run multiple times for different sets of data (which can be
kept in multiple rows in the data sheet).ü
Changes made in the test data don’t affect the test scripts in any way and vice versa.ü
Disadvantages of Data Driven Framework
Additional effort and good technical expertise is required to create functions that connect to the external data sources to retrieve the
data.ü
Additional amount of time is required in identifying which external data source to use and deciding how the data should be stored or
grouped in that external data source.ü
3.Modular framework
Modular Framework is the approach where all the test cases are first analyzed to find out the reusable flows. Then while scripting,
all these reusable flows are created as functions and stored in external files and called in the test scripts wherever required.
4.Hybrid framework.
Hybrid Framework is a framework that is created by combining different features of any of the frameworks mentioned above.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 21/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Based upon your requirements, you can combine the features of any of the above frameworks to come up with your own version of
Hybrid Framework.
5. Once it is done, select “Virtual Devices” to create one for you. Click on “New” and enter some name. Target as “Android 2.2 – API
Level 8” (or) select from dropdown. Select Size as “512” and “Built-in” to be “WVGA854” and click on “Create AVD”.
http://2.bp.blogspot.com/-yi1YUT8iqUM/UPPrxtMbzII/AAAAAAAAAFE/quUV0BlEi4E/s320/AVD+Manager+start.png
6. Once done select the Virtual device you created and click on Start. You can find the “Start” button on the right panel in the above
shown image. Clicking “Start” will launch another pop-up, just say “Launch” and proceed.
7.Once its opened you can see the image as below
http://4.bp.blogspot.com/-BD8frcSBY3Y/UPPr-FhG-DI/AAAAAAAAAFM/Zbjmgq66iOk/s320/Android+Virtual+Mobile.png
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 22/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
ad.findElement(By.name("Email")).sendKeys("type your email");
ad.findElement(By.name("Passwd")).sendKeys("type password");
ad.findElement(By.name("signIn")).click();
System.out.println("Opened");
ad.close();
}
}
ANT-Generating Selenium HTML and XSLT reports using TestNG-xslt through Ant
Selenium – Use Ant to Generate HTML and XSLT Reports
Apache Ant is an open source build tool. A build tool can be used to compile the source code, creating the build artifacts such as JAR,
WAR, and EAR files. Some of the other usage of ANT is to run unit tests, do the application deployment on containers such as JBoss,
Tomcat, WebSphere, WebLogic, GlassFish, etc, and to run Automated Selenium Tests.
Ant is a powerful build tool and also is very much extensible. There are several open source Ant libraries available which need to be
just downloaded, unzipped, and copied (JAR file) into the Ant’s “lib” folder. Once the library file is copied, then we can utilize the
“Tasks” in the Ant’s build.xml file. Ant’s “contrib library, jsch library, etc” are the best examples for such libraries.
Install and configure ANT
1. Download ANT from Apache web site – ANT download link
2. Unzip the ant and copy to C:\Ant folder
3. Now we need to configure environment variables: ANT_HOME
4. Navigate to environment variables and click on new button.
5. Enter Variable name as ANT_HOME and Variable Value as C:\apache-ant-1.8.4.Then click on OK button
http://2.bp.blogspot.com/-KJdbNcJIi08/URoNKlytgwI/AAAAAAAAAFk/58Fk5fcbwxU/s1600/ANT_HOME.png
6. Now select the PATH and click on EDIT button
7. Now give the semicolon (;) at the end and add ANT path up to bin folder
http://3.bp.blogspot.com/-DhVg13zTN2I/URoNbwAVOhI/AAAAAAAAAFs/-CPGtSjggVE/s1600/PATH.png
8. Now click on OK button and go to command prompt and type ANT.
“It will give message as build.xml not fount”
9. Now go to eclipse and add below build.xml file to your selenium project.
http://1.bp.blogspot.com/-cn6fLEeYhwk/URoNvXRbHoI/AAAAAAAAAF0/dW83SE6YbMA/s320/build.XML+File.png
http://2.bp.blogspot.com/-H0K0u6qHZic/URoRb4yiqeI/AAAAAAAAAGc/IYhTgoVR9kU/s320/build.XML+Code1.png
10. In this Build.xml file give the path where you copied all the required jar file.(Copy all the required jar files in any of the folder and
mention that path)
11. Now go to command prompt and type > ant clean
It will clean all the required files related to ant.
12. Now type > ant compile
It will compile your code
13. Now type >ant run
http://2.bp.blogspot.com/-YBhDw1xJZ-g/URoN9x1kOjI/AAAAAAAAAF8/ZlHnrKqUbkc/s320/ANT-TestNG-HTML+Report.png
It will run your program and will generate HTML reports.
Generating selenium reports using TestNG-xslt through Ant
TestNG-xslt generates user friendly reports using the TestNG results output (testng-results.xml). Its uses the pure XSL for report
generation and Saxon as an XSL2.0 implementation
For generating testng-xslt report for your project do the following:
1. Download the testng-xslt
2. Unzip and copy the testng-results.xsl from the testng-xslt folder(testng-xslt-1.1\src\main\resources) to your own project folder.
3. Now copy the saxon library from (testng-xslt-1.1\lib\saxon-8.7.jar)to where you created a folder for which you copied all the JAR
files to run ANT.
4. Modify your build.xml of ant and add the following target to it.
http://4.bp.blogspot.com/-xD0coAziy6A/URoRq4uyp-I/AAAAAAAAAGk/eExJBUaOKo0/s320/XSLT+code.png
5. Now go to command prompt and follow below steps to generate XSLT reports.
6. Now type > ant clean
It will clean all the required files related to ant.
7. Now type > ant compile
It will compile your code
8. Now type >ant run
It will run your program.
9. Now type >ant xsltreports
It will generate xslt reports as below
http://1.bp.blogspot.com/-aTX0qUA5IgA/URoOQocwmqI/AAAAAAAAAGE/hAateaXS-Fw/s320/ANT-TestNG-XSLT+Report.png
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 23/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Say download at “C:\android ” location
Go to unzipped folder and click on “Android SDK Manager” and install the following:
a.Tools
b.Extras
c.Android API’s as per your choice (Say Android 2.2 , Android 4.0)
6. Now start the Android AVD (Which has been created in Step 4) by following below in your Eclipse
Window >>AVD Manager>> Select the created AVD and click on “Start”
8. Now from the command prompt, go to the “Platform-tools” folder of the unzipped Android SDK
cd "C:\android\android-sdk-windows\platform-tools"
11. Now setup the port forwarding in order to forward traffic from the host machine to the emulator by running the following
command
adb -s emulator-id forward tcp:8080 tcp:8080
Snippet:
import java.sql.*;
import javax.sql.*;
try
{
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl,username,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
dbtime = rs.getString(1);
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 24/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
System.out.println(email);
} //end while
con.close();
} //end try
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
} //end main
} //end class
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 25/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Refer automation link
7. Which is the best way to locate an element?
Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to
document.getElementById(), which is optimized by many browsers.
Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but
it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing
the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and
the JavaScript engine in legacy versions of IE really is that much slower.
If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as
flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.
8. Why we refer Firefox driver to the web driver inheritance.
web Driver driver = new FireFoxDriver();
WebDriver is an interface which contain several abstract methods such as get(...), findElamentBy(...) etc.
We simply create reference of web Driver and we can assign objects (Firefox driver, CromeDriver, IEDriver, Andriod driver etc) to it.
Ex :
WebDriver driver = new FireFoxDriver();-----------(1)
If we are using (1) we can do the same thing by using
FireFoxDriver driver = new FireFoxDriver();---------(2)
We can use (1) and (2) for same purpose but if we want to switch to another browser in same program
then again we have to create the object of other class as for example
CromeDriver driver = new CromeDriver();.
creating object of several class is not good. So we create the reference of WebDriver and
we assign the objects of another class as for example
WebDriver driver; // it is created only one time in the program
driver = new FireFoxDriver();// any where in the program
driver = new CromeDriver(); // any where in the program
9. What are the features of TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from
unit testing (testing a class in isolation of the others) to integration testing (testing entire
systems made of several classes, several packages and even several external frameworks,
such as application servers). You can use test suite,annotations, automatically generation
of report and much more.
10. What is the difference between thread.Sleep() and selenium. Set Speed ("2000")?
If the application is taking time to load the page then we use selenium.waitforpageload(" "). This command is doesn’t wait upto the
given time whenever the page load is completed.
If the application is taking time to refresh the page, then we use Thread. Sleep ( ).it is a standard wait it simply wait to the given time.
selenium.setSpeed
1. Takes a single argument in string format
Ex: selenium.setSpeed("2000") - will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in set Speed.
thread.sleep
1. Takes a single argument in integer format
ex: thread. Sleep(2000) - will wait for 2 seconds
2. Waits for only once at the command given at sleep.
11. In what situation selenium finding element get fails?
-->Element loading issue
-->Dynamic id of web element
12. What is the difference between "GET" and "NAVIGATE" to open a web page in selenium web driver?
Get method will get a page to load or get page source or get text that's all whereas navigate
will guide through the history like refresh, back, forward.For example if we want to move
forward and do some functionality and back to the home page this can be achieved
through navigate() only. driver.get will wait till the whole page gets loaded and driver.navigate
will just redirect to that page and will not wait
13. Please tell me the difference b/w implicitly Wait and Explicit wait.
Implicit Wait sets internally a timeout that will be used for all consecutive Web Element searches. It will try lookup the element
again and again for the specified amount of time before throwing a NoSuchElementException if the element could not have been
found. It does only this and can't be forced into anything else - it waits for elements to show up.
Explicit Wait or just Wait is a one-timer used by you for a particular search. It is more extendible in the means that you can set it up
to wait for any condition you might like. Usually, you can use some of the prebuilt Expected Conditions to wait for elements to
become clickable, visible, invisible, etc., or just write your own condition that suits your needs.
14. How we can retrieve the dynamically changing Ids?
When we login Facebook the login label's id
changes dynamically thus resulting in failure.
We have a hierarchy of locators and Facebook Is dynamic in nature,so we are not able to
use "id" for identification for after that we have remaining 7 locator's for that :2. xpath ()..
3. name..4. css.. 5. link text.. 6. partiallinktext...7.tag name. so u can use any one for
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 26/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
identifying it. Most probably u can use "xpath" or "css-locator" and if there r tag then
link text or partial-link text. it depend on u . But we never use id's in Ajax application
because it’s not possible.
15.What is the difference between driver.Close() and driver.Quit () method?
Close() - It is used to close the browser or page currently which is having the focus.
Quit() - It is used to shut down the web driver instance or destroy the web driver instance
(Close all the windows)
16. How to scroll web element?--not browser—
FirefoxProfile profile=new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver=new FirefoxDriver(profile);
driver.navigate("http://jqueryui.com/draggable/");
Thread.sleep(6000L);
WebElement element=driver.findElement(By.xpath("//div[@id='draggable']"));
Actions actn=new Actions(driver);
actn.dragAndDropBy(element, 50, 50).build().perform();
}
17. What is the basic use of Firefox profiles and how can we use them using selenium?
A profile in Firefox is a collection of bookmarks, browser settings, extensions, passwords,
and history; in short, all of your personal settings.
We use them to change user agent, changing default download directory, changing versions etc.
http://code.google.com/p/selenium/wiki/FirefoxDriver
18. Customize the name of file going to be downloaded?
You have to download AUTO IT.exe file and has to be install
and later you have create .au3 file (in this file you have to specify the commands in
VB script like your file name, where have to save, it will be easy may be 3 or 4 steps )
using AUTOIT...then right click the .au3 file you have to compile ....after that you will
get the .exe file with the name of .au3 file ..In eclipse you will give the code like this
<----processbuildder .exe="" .start="" au3="" file="" of="" path="" processbuilder="" ps="new" the="">
19. How to handle internationalisation through web driver?
FirefoxProfile profile = new FirefoxProfile();
profile.set Preference("intl.accept_languages","jp");
Web driver driver = new FirefoxDriver(profile); driver.get(google.com) will open google in
Japanese Lang
20. How to overcome same origin policy through web driver?
Proxy server.
DesiredCapabilities capability=new DesiredCapabilities.firefox();
capability.setCapability(CapabilityType.PROXY,"your desire proxy")
WebDriver driver=new FirefoxDriver(capability);
21. How to put text in Facebook search box using selenium web driver.
driver.findElement(By.xpath("//div[contains(@class, '_586i')]")).sendKeys("abc");
24. How can we get the font size, font color, font type used for a particular text on a web page using Selenium web driver?
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);
driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);
25. How to run tests in multiple browser parallel? Is there any other option other than selenium grid?
26. How to prepare Customized html Report using TestNG in hybrid framework.
Below are the 3 ways:
• Junit: with the help of ANT.
• TestNG: using inbuilt default.html to get the HTML report. Also XST reports from ANT,
Selenium, TestNG combination.
• Using our own customized reports using XSL jar for converting XML content to HTML.
27. “What’s the hierarchy of TestNG annotations? Explain me about annotation hierarchy & execution order?
Please find hierarchy below:
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 27/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
1. org.testng.annotations.Parameters (implements java.lang.annotation.Annotation)
2. org.testng.annotations.Listeners (implements java.lang.annotation.Annotation)
3. org.testng.annotations.Test (implements java.lang.annotation.Annotation)
4. org.testng.annotations.AfterMethod (implements java.lang.annotation.Annotation)
5. org.testng.annotations.BeforeTest (implements java.lang.annotation.Annotation)
6. org.testng.annotations.BeforeMethod (implements java.lang.annotation.Annotation)
7. org.testng.annotations.Optional (implements java.lang.annotation.Annotation)
8. org.testng.annotations.AfterTest (implements java.lang.annotation.Annotation)
9. org.testng.annotations.Guice (implements java.lang.annotation.Annotation)
10. org.testng.annotations.BeforeGroups (implements java.lang.annotation.Annotation)
11. org.testng.annotations.ExpectedExceptions (implements java.lang.annotation.Annotation)
12. org.testng.annotations.TestInstance (implements java.lang.annotation.Annotation)
13. org.testng.annotations.NoInjection (implements java.lang.annotation.Annotation)
14. org.testng.annotations.AfterSuite (implements java.lang.annotation.Annotation)
15. org.testng.annotations.AfterClass (implements java.lang.annotation.Annotation)
16. org.testng.annotations.AfterGroups (implements java.lang.annotation.Annotation)
17. org.testng.annotations.DataProvider (implements java.lang.annotation.Annotation)
18. org.testng.annotations.BeforeSuite (implements java.lang.annotation.Annotation)
19. org.testng.annotations.BeforeClass (implements java.lang.annotation.Annotation)
20. org.testng.annotations.Factory (implements java.lang.annotation.Annotation)
21. org.testng.annotations.Configuration (implements java.lang.annotation.Annotation)
22. org.testng.annotations.ObjectFactory (implements java.lang.annotation.Annotation)
Useful link:
http://www.guru99.com/all-about-testng-and-selenium.html
28. How the TestNG interacts with Selenium Core?
Explain me steps and internal architecture?"
http://www.guru99.com/all-about-testng-and-selenium.html
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
31. Can u send a code for printing in selenium?
There are two cases:
Case1. Any hyperlink/button on a web page, n clicking that link/button a print dialog box
opens. (Performing an action on web page)
Case2.or do u want to open print dialog box within ur own script, not by performing any
action on web page.
So If Case 1: just a call for WebElement.click() event will work to open it.
If Case 2: Call a Printer Job object (Use Awt API).
For code: Google it.
http://code.google.com/p/selenium/issues/detail?id=1815
32. How to find broken images in a page using Selenium Web driver.
1. Get xpath and then using tag name; get all the links in the page
2. Click on each and every link in the page
3. In the target page title, look for 404/500 error.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 28/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
33. How to handle Ajax popup window?
By using getWindowHandles() and obj.switchTo.window(windowid) we can handle popups using
explicit wait and driver.swtchT0.window("name") commands for your requirements.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
@BeforeTest
@Parameters({ "BROWSER" })
public void setup(String BROWSER) {
System.out.println("Browser: " + BROWSER);
if (BROWSER.equals("FF")) {
System.out.println("Firefox Browser is selected");
driver = new FirefoxDriver();
} else if (BROWSER.equals("IE")) {
System.out.println("Internet Explorer Browser is selected");
driver = new InternetExplorerDriver();
} else if (BROWSER.equals("HU")) {
System.out.println("Html Unit Browser is selected");
driver = new HtmlUnitDriver();
} else if (BROWSER.equals("CH")) {
System.out.println("Google chrome Browser is selected");
driver = new ChromeDriver();
}
}
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 29/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
@Test
public void testParallel() throws Exception {
driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html");
}
}
above sample program BROWSER is a variable which value would be passed from TestNG.xml and TestNG.xml
and it will run the test multiple time each time BROWSER value would be set with different browser name and
test will check the BROWSER value and decide which browser test will run.
48. “Suppose developer changed the existing image to new image with same xpath. Is test case pass or fail?"
Pass
50. How does u handle dynamic elements without using xpath (with example?)
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 30/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
By using classname or css.
53. Which repository you have used to store the test scripts?
I have created scripts in excel file and store them in Test cases folder under src .
54. How to work with radio button in web driver?
We can select the value from the drop down by using 3 methods.
WebElement e = driver.findElement(By.id("44"));
Select selectElement=new Select(e);
// both of the below statements will select first option in the weblist
selectElement.selectByVisibleText("xyz");
selectElement.selectByValue("1");
57. In frame if no frame Id as well as no frame name then which attribute I should consider throughout our script.
You can go like this.....driver.findElements(By.xpath("//iframe"))...
Then it will return List of frames then switch to each and every frame and search for
the locator which you want then break the loop
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 31/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Test Case class then we can utilise “@BeforeClass” annotation.
How to highlight an object like qtp/uft does through selenium and java?
public void highlightElement(WebDriver driver, WebElement element) {
for (int i = 0; i < 2; i++)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
}}
Call the highlightElement method and pass webdriver and WebElement which you want to highlight as arguments.
65. What are the different assertions in SIDE?
Assertions are like Assessors, but they verify that the state of the application conforms
to what is expected. Examples include "make sure the page title is X" and "verify that this
check box is checked".
All Selenium Assertions can be used in 3 modes: "assert", "verify", and "waitFor".
For example, you can "assertText", "verifyText" and "waitForText". When an "assert" fails, the test is aborted. When a "verify" fails,
the test will continue execution, logging the failure. This allows a single "assert" to ensure that the application is on the correct page,
followed by a bunch of "verify" assertions to test form field values, labels, etc.
"waitFor" commands wait for some condition to become true (which can be useful for testing Ajax applications). They will succeed
immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the
current timeout setting (see the setTimeout action below).
http://selenium-tutorial.blogspot.in/2013/03/selenium-webdriver-assertions.html
66. How to store a value which is text box using web driver?
driver.findElement(By.id("your Textbox")).sendKeys("your keyword");
67. How to handle alerts and confirmation boxes. Confirmation boxes and Alerts are handled in same way in selenium.
var alert = driver.switchTo().alert();
alert.dismiss(); //Click Cancel or Close window operation
alert.accept(); //Click OK
Handle Confirmation boxes via JavaScript,
driver.executeScript("window.confirm = function(message){return true;};");
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 32/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
A name or ID.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
A previously found WebElement.
Select a frame using its previously located WebElement.
Get the frame by it's id/name or locate it by driver.findElement() and you'll be good.
71. What is actions class in web driver?
Actions class with web Driver help is Sliding element, Resizing an Element, Drag & Drop,
hovering a mouse, especially in a case when dealing with mouse over menus.
Dragging & Dropping an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testDragandDrop {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://jqueryui.com/resources/demos/droppable/default.html");
WebElement draggable = driver.findElement(By.xpath("//*[@id='draggable']"));
WebElement droppable = driver.findElement(By.xpath("//*[@id='droppable']"));
Actions action = new Actions(driver);
action.dragAndDrop(draggable, droppable).perform();
}
}
Sliding an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testSlider {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://jqueryui.com/resources/demos/slider/default.html");
WebElement slider = driver.findElement(By.xpath("//*[@id='slider']/a"));
Actions action = new Actions(driver);
Thread.sleep(3000);
action.dragAndDropBy(slider, 90, 0).perform();
}
}
Re-sizing an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testResizable {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://jqueryui.com/resources/demos/resizable/default.html");
WebElement resize = driver.findElement(By.xpath("//*[@id='resizable']/div[3]"));
Actions action = new Actions(driver);
action.dragAndDropBy(resize, 400, 200).perform();
}
}
72. Difference between the selenium1.0 and selenium 2.0?
Selenium 1 = Selenium Remote Control.
Selenium 2 = Selenium Web driver, which combines elements of Selenium 1 and Web driver.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 33/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
findElement() :
Find the first element within the current page using the given "locating mechanism".
Returns a single WebElement.
Syntax: WebElement findElement(By by)
Ex:
driver.get("http://ruchi-myseleniumblog.blogspot.in/");
WebElement widget = driver.findElement(By .xpath(".//*[@id='BlogArchive1_ArchiveList']"));
widget.click();
findElements() :
Find all elements within the current page using the given "locating mechanism".
Returns List of WebElements.
Syntax:
WebElement ullist = driver.findElement(By.className("posts"));
List posts = ullist.findElements(By.tagName("li"));
System.out.println("List of Posts are Below");
for (int i = 0; i < posts.size(); i++) {
String post = posts.get(i).findElement(By.tagName("a")).getText();
System.out.println(post);
}
74. How to take the screen shots in seelnium2.0?
//store screenshots
public static void captureScreenShot(String filePath) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(filePath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
75. What is the default time for selenium Ide and webdriver?
Default timeout in selenium ide is 30 seconds.
For web driver go to below URL:
http://assertselenium.com/2013/01/29/webdriver-wait-commands/
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 34/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
}
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
return "Fail - " + e.getMessage();
}
}
80. What is default port no?
4444
86. Can you explain Junit Annotation? If there are 1000 test cases. 500 test cases are executed. How will you execute the rest of the
test cases by using annotation?"
The annotations generated with JUnit 4 tests in Selenium are:
1. @Before public void method() - Will perform the method() before each test. This method
can prepare the test
2. @Test public void method() - Annotation @Test identifies that this method is a test
method.environment,e.g. read input data, initialize the class)
3. @After public void method() - Test method must start with test@Before - this annotation
is used for executing a method before
88. "I want to find the location of ""b"" in the below code, how can I find out without using xpath, name, id, csslocator, index.
a
b
c
· driver.findElement(By.xpath("//*[contains(text(),'b')]")).click(); or
//div/button[contains(text(),'b']
90. Name 5 different exceptions you had in selenium web driver and mention what instance you got it and how do you resolve it?
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 35/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
WebDriverException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
• WebDriverException
WebDriver Exception comes when we try to perform any action on the non-existing
driver.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.close();
driver.quit();
• NoAlertPresentException
When we try to perform an action i.e., either accept() or dismiss() which is not required
at a required place; gives us this exception.
try{
driver.switchTo().alert().accept();
}
catch (NoAlertPresentException E){
E.printStackTrace();
}
• NoSuchWindowException
When we try to switch to an window which is not present gives us this exception:
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();
In the above snippet, line 3 throws us an exception, as we are trying to switch to an
window that is not present.• NoSuchFrameException
• Similar to Window exception, Frame exception mainly comes during switching between
the frames.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();
In the above snippet, line 3 throws us an exception, as we are trying to switch to an
frame that is not present.
• NoSuchElementException
This exception is thrown when we WebDriver doesn’t find the web-element in the DOM.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();
• TimeoutException
Thrown when a command does not complete in enough time.
All the above exceptions were handled using try catch exceptions.
91. How do you manage the code versions in your project?
Using SVN or other versioning tools
92. Latest version of Firefox and selenium in market and the version on which you are testing which you are testing.
FF Latest version till Dec,2013 for windows7,64 bit :26.0.I use FF 25.0.1 (ur ans. may differ)
Selenium web driver latest version till dec,2013- 2.39.0 I use selenium 2.37 see latest at
http://www.seleniumhq.org/download/
93. How to know all the methods supported in web driver and its syntax.
In Org.openqa.selenium package, web driver interface has all the main methods that can
be used in Selenium Web driver
HTTP://docs.seleniumhq.org/docs/03_webdriver.jsp
94. How do you create html test report from your test script?
• I would see below 3 ways:
• Junit: with the help of ANT.
• TestNG: using inbuilt default.html to get the HTML report. Also XLST reports from ANT,
Selenium, TestNG combination.
• Using our own customized reports using XSL jar for converting XML content to HTML.
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 36/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
Opera Y Y Y
Chrome Y Y Y
96. Can you explain Selenium Mobile Automation?
https://code.google.com/p/selenium/wiki/AndroidDriver
http://manojhans.blogspot.in/2013/08/native-android-apps-automation-with.html
97. What mobile devices it may Support?
Selenium Web driver supports all the mobile devices operating on Android, IOS operating Systems
Android – for phones and tablets (devices & emulators)
iOS for phones (devices & emulators) and for tablets (devices & emulators)
98. What is the difference between single and double slash in Xpath?
/
1.It starts selection from the document node
2. It Allows you to create 'absolute' path expressions
3. e.g “/html/body/p” matches all the paragraph elements
//
1. It starts selection matching anywhere in the document
2. It Allows you to create 'relative' path expressions
3. e.g“//p” matches all the paragraph elements
99. What are the test types supported by Selenium?
Selenium supports UI and functional testing. As well it can support performance testing
for reasonable load using selenium grid.
8 comments:
Thanks for sharing an information to us. If someone wants to know about websites and SEO Service. I think this is the right
place for you!
Digital Marketing
SEO Company
Reply
The above article "Selenium ques $ans -4" is more informative. This is more helpful for our selenium training in chennai. Thanks
for sharing
Reply
Reply
This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up
selenium online training
iframes in selenium
selenium with python training
Reply
Very nice post..After reading your post,thanks for taking the time to discuss this, I feel happy about and I love learning more
about this topic.
Selenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur |
Selenium Training in tambaram | Selenium Training in velachery
Reply
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 37/38
05/01/2023 20:12 Selenium Test Automation: Selenium ques $ans -4
MotherHost 25 March 2022 at 20:44
Windows Hosting
Linux Hosting
Shared Web Hosting
Reply
Reply
Reply
seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 38/38