Vous êtes sur la page 1sur 171

05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest

 Hey, on recrute ! Dépose ton CV ici

Test ISTQB Foundation en


ligne
1 - QU'EST-CE QUE LE DÉBOGAGE ?

 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 ?

 1. Le testeur n’est pas impliqué dans cette phase


 2. Le testeur effectue une revue des spécifications afin de détecter au plus tôt les points à éclaircir ou à
corriger
 3. Le testeur rédige une partie des spécifications
 4. Le testeur rédige l’intégralité des spécifications

3 - UN TEST AUTOMATISÉ EST EN ERREUR, POURTANT L’APPLICATION FONCTIONNE CORRECTEMENT. COMMENT CELA
S’APPELLE-T-IL ?

 1. Un faux positif


 2. Un test non-fonctionnel
 3. Un faux négatif
 4. Un test automatisé n’est en erreur que si l’application présente une anomalie. En revanche, l’anomalie
décelée par le test automatisé n’est pas toujours celle qui était anticipée au moment de son implémentation.
 Temps restant : 25 min 56 sec Version anglaise 

https://hightest.nc/ressources/test-istqb.php 1/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest

4 - LA VOCATION DES TESTS FONCTIONNELS DYNAMIQUES AUTOMATISÉS EST DE :

 1. Trouver certains défauts du logiciels sans exécuter celui-ci


 2. Se prémunir contre les régressions des fonctionnalités entre deux versions du produit
 3. Evaluer automatiquement l'utilisabilité d'une application
 4. Mesurer automatiquement les performances d’une application

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.

6 - COMMENT SE CALCULE UN RISQUE ?

 1. Risque = Impacts en cas d’occurrence / Bénéfices en cas de non-occurrence


 2. Risque = Somme de la gravité des impacts possibles
 3. Risque = Probabilité d’occurrence x Impact en cas d’occurrence
 4. Il n’est pas recommandé de calculer les risques, car le résultat du calcul est susceptible de créer des biais
et d’induire l’équipe de test en erreur.

7 - QU’EST-CE QU’UNE PARTITION D’ÉQUIVALENCE ?

 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. Un outil de test management


 2. Un graphe d’appel
 3. Un diagramme d’états et de transitions
 4. Une table de décisions

9 - UN TEST UNITAIRE EXÉCUTE LA FONCTION SUIVANTE AVEC L’ARGUMENT $SOLDES = TRUE.

$THEME = 'IMPRIMÉ ZÈBRE ET OR';

FUNCTION CREERPANCARTERAYON(BOOLEAN $SOLDES){


ECHO 'DÉCOUVREZ NOTRE COLLECTION SUR LE THÈME DE LA SEMAINE : '.$THEME;
IF ($SOLDES) {
ECHO '. LES ARTICLES DE CE RAYONS SONT EN SOLDES : ILS NE SERONT NI REPRIS, NI ÉCHANGÉS.';
}
}

I. LA COUVERTURE DES FONCTIONS DE CETTE PORTION DE CODE EST ASSURÉE.


II. LA COUVERTURE DES INSTRUCTIONS DE CETTE PORTION DE CODE EST ASSURÉE.
III. LA COUVERTURE DES DÉCISIONS DE CETTE PORTION DE CODE EST ASSURÉE.
IV. LA COUVERTURE DES CHEMINS DE CETTE PORTION DE CODE EST ASSURÉE.
QUELLES PROPOSITIONS LISTÉES CI-DESSUS SONT JUSTES ?

 1. I et II
 2. I et III
 3. II et IV
 4. III et IV

 Temps restant : 25 min 56 sec Version anglaise 

https://hightest.nc/ressources/test-istqb.php 3/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest

10 - L’INDÉPENDANCE DE L’ÉQUIPE DE TEST VIS-À-VIS DE L’ÉQUIPE DE DÉVELOPPEMENT FAVORISE L’IMPARTIALITÉ DES


TESTS. MAIS ELLE PRÉSENTE AUSSI DES RISQUES. LEQUEL N’EN FAIT PAS DIRECTEMENT PARTIE ?

 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 ?

 1. Les risques techniques et les risques fonctionnels


 2. Les risques quantitatifs et les risques qualitatifs
 3. Les risques contextuels et les risques permanents
 4. Les risques projet et les risques produit

12 - PARMI LES ACTIVITÉS SUIVANTES, LESQUELLES PEUVENT ÊTRE RÉALISÉES DE MANIÈRE INFORMELLE ?

 1. Les tests d’acceptation


 2. Les revues de code
 3. Les inspections
 4. Le suivi de l’avancement des tests

13 - QU’EST-CE QU’UNE EXIGENCE NON-FONCTIONNELLE ?

 1. Une exigence laissée de côté suite à un arbitrage de l’équipe de test


 2. Une exigence contredite par d’autres exigences
 3. Une exigence ne se rapportant pas aux fonctionnalités
 4. Une exigence qui n’impacte pas l’expérience utilisateur

14 - L’ÉQUIPE DE DÉVELOPPEMENT VIENT DE FINALISER LE DÉVELOPPEMENT D’UN SITE CONTENANT BEAUCOUP


D’ANIMATIONS (CARROUSEL D’IMAGES, POPUPS…) LE CLIENT SOUHAITE S’ASSURER QUE CE GRAND NOMBRE
D’ANIMATION NE RALENTIT PAS TROP LE CHARGEMENT DU SITE. QUEL TYPE DE TEST EST TOUT INDIQUÉ DANS CE CAS-
LÀ ?
 Temps restant : 25 min 56 sec Version anglaise 

https://hightest.nc/ressources/test-istqb.php 4/6
05/01/2023 19:14 Test ISTQB en ligne, niveau Fondation - Hightest

 1. Test de montée en charge


 2. Test de performance
 3. Test de robustesse
 4. Test de stress

15 - LA QUALITÉ EST DÉFINIE COMME...

 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

16 - COCHEZ LA FORMULATION JUSTE.

 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

18 - DANS QUEL ORDRE SE DÉROULENT EN PRINCIPE LES DIFFÉRENTS NIVEAUX DE TESTS ?

 1. Tests de composants, tests d'intégration, tests système, tests d'acceptation


 2. Tests de composants, tests système, tests d'acceptation, tests d'intégration
 3. Tests de composants, tests d'acceptation, tests système, tests d'intégration
 4. Tests de composants, tests d'acceptation, tests d'intégration, tests système

19 - L'AGILITÉ S'OPPOSE-T-ELLE AU TEST ?

 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é.

20 - QUAND FAUT-IL COMMENCER À TESTER ?

 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É !

 Temps restant : 25 min 56 sec Version anglaise 

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 !

Qu'est-ce que le débogage ?

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.

Solution

Voir chapitre 1.1.2, p. 14.

Vous n'avez pas trouvé cette réponse.

Lors de la phase de conception des spécifications, quelle pratique est la plus


adéquate ?

1. Le testeur n’est pas impliqué dans cette phase


2. Le testeur effectue une revue des spécifications afin de détecter au plus tôt les
points à éclaircir ou à corriger
3. Le testeur rédige une partie des spécifications
4. Le testeur rédige l’intégralité des spécifications

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'.

Vous n'avez pas trouvé cette réponse.

Un test automatisé est en erreur, pourtant l’application fonctionne correctement.


Comment cela s’appelle-t-il ?
1. Un faux positif
2. Un test non-fonctionnel
3. Un faux négatif
4. Un test automatisé n’est en erreur que si l’application présente une anomalie. En
revanche, l’anomalie décelée par le test automatisé n’est pas toujours celle qui était
anticipée au moment de son implémentation.

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.

Vous n'avez pas trouvé cette réponse.

La vocation des tests fonctionnels dynamiques automatisés est de :

1. Trouver certains défauts du logiciels sans exécuter celui-ci


2. Se prémunir contre les régressions des fonctionnalités entre deux versions du
produit
3. Evaluer automatiquement l'utilisabilité d'une application
4. Mesurer automatiquement les performances d’une application

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.

Vous n'avez pas trouvé cette réponse.

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

Voir le chapitre 4.4.2, sur les tests exploratoires.

Vous n'avez pas trouvé cette réponse.

Comment se calcule un risque ?

1. Risque = Impacts en cas d’occurrence / Bénéfices en cas de non-occurrence


2. Risque = Somme de la gravité des impacts possibles
3. Risque = Probabilité d’occurrence x Impact en cas d’occurrence
4. Il n’est pas recommandé de calculer les risques, car le résultat du calcul est
susceptible de créer des biais et d’induire l’équipe de test en erreur.

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.

Vous n'avez pas trouvé cette réponse.

Qu’est-ce qu’une partition d’équivalence ?

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.
3. La somme de tous les comportements possibles permettant d’effectuer une même
action au sein d’un applicatif donné.
4. Un recueil de règles de nommages applicable au développement d’un applicatif
donné.

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.

Vous n'avez pas trouvé cette réponse.

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. Un outil de test management


2. Un graphe d’appel
3. Un diagramme d’états et de transitions
4. Une table de décisions

Solution

Voir chapitre 4.2.3. La table pourra ressembler à celle-ci :


Paiement en espèces Paiement en espèces
Cas
possible impossible
Non abonné X
Abonné, carte non activée X
Abonné, carte périmée X
Abonné, carte non activée et
X
périmée
Abonné, carte activée et non
X
périmée

Vous n'avez pas trouvé cette réponse.

Un test unitaire exécute la fonction suivante avec l’argument $soldes = true.


$theme = 'Imprimé zèbre et or';

function creerPancarteRayon(boolean $soldes){


echo 'Découvrez notre collection sur le thème de
la semaine : '.$theme;
if ($soldes) {
echo '. Les articles de ce rayons sont en soldes
: ils ne seront ni repris, ni échangés.';
}
}
I. La couverture des fonctions de cette portion de code est assurée.
II. La couverture des instructions de cette portion de code est assurée.
III. La couverture des décisions de cette portion de code est assurée.
IV. La couverture des chemins de cette portion de code est assurée.
Quelles propositions listées ci-dessus sont justes ?

1. I et II
2. I et III
3. II et IV
4. III et IV

Solution

Toutes les fonctions (c’est-à-dire une : creerPancarteRayon) ont été testées ; la


couverture des fonctions est donc assurée. Avec l’argument soldes à true, le test
unitaire est amené à exécuter chaque ligne du code ; la couverture des instructions est
donc assurée. En revanche, la couverture des décisions n’est pas assurée, car il
faudrait pour cela tester aussi la fonction avec l’argument soldes à false. A fortiori, la
couverture des chemins n’est pas assurée non plus. Voir chapitre 4.3, et le glossaire du
syllabus.

Vous n'avez pas trouvé cette réponse.

L’indépendance de l’équipe de test vis-à-vis de l’équipe de développement


favorise l’impartialité des tests. Mais elle présente aussi des risques. Lequel n’en
fait pas directement partie ?

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

Solution

Les équipes de développement sont parfois susceptibles de se reposer sur l’équipe de


test, estimant qu’il n’est plus de leur ressort d’assurer la qualité de leur application. Il
peut également arriver que l’équipe de test soit si indépendante que la communication
en pâtisse ; dans ce cas, des incompréhensions peuvent ralentir le projet. Enfin, une
équipe de test indépendante peut être amenée à intervenir seulement à la fin du projet,
ce qui constitue un goulet d’étranglement. Manquer de légitimité auprès du client ne
constitue pas un risque directe de l’indépendance du test. Voir chapitre 5.1.1.
Vous n'avez pas trouvé cette réponse.

Tout projet de test est soumis à deux grandes familles de risques. Lesquels ?

1. Les risques techniques et les risques fonctionnels


2. Les risques quantitatifs et les risques qualitatifs
3. Les risques contextuels et les risques permanents
4. Les risques projet et les risques produit

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.

Vous n'avez pas trouvé cette réponse.

Parmi les activités suivantes, lesquelles peuvent être réalisées de manière


informelle ?

1. Les tests d’acceptation


2. Les revues de code
3. Les inspections
4. Le suivi de l’avancement des tests

Solution

Les tests d’acceptation doivent déterminer si l’applicatif correspond au besoin


initialement exprimé ; ils doivent suivre un processus formel en ce qu’ils engagent une
prise de décision (GO/NO GO). Les inspections sont une technique de test statique qui
se base sur des procédures documentées (par exemple des checklists) pour détecter
les défauts du logiciel. Le suivi de l’avancement des tests donne lieu à des métriques
permettant d’évaluer le temps passé sur les différentes activités de test, le coût des
tests, la quantité de défauts trouvés et corrigés… Dans la liste, seule la revue de code
peut être réalisée de manière informelle. Par exemple, « l’analyse par-dessus l’épaule
», pilotée par l’auteur, permet à un autre développeur de fournir une relecture rapide
des modifications effectuées. Voir chapitre 3.2 sur les processus de revue.

Vous n'avez pas trouvé cette réponse.


Qu’est-ce qu’une exigence non-fonctionnelle ?

1. Une exigence laissée de côté suite à un arbitrage de l’équipe de test


2. Une exigence contredite par d’autres exigences
3. Une exigence ne se rapportant pas aux fonctionnalités
4. Une exigence qui n’impacte pas l’expérience utilisateur

Solution

Une exigence non-fonctionnelle peut se rapporter à des attributs de l’application tels


que sa fiabilité, son rendement, sa performance, son utilisabilité, sa maintenabilité, sa
portabilité… Voir chapitre 2.3.2.

Vous n'avez pas trouvé cette réponse.

L’équipe de développement vient de finaliser le développement d’un site


contenant beaucoup d’animations (carrousel d’images, popups…) Le client
souhaite s’assurer que ce grand nombre d’animation ne ralentit pas trop le
chargement du site. Quel type de test est tout indiqué dans ce cas-là ?

1. Test de montée en charge


2. Test de performance
3. Test de robustesse
4. Test de stress

Solution

Un objectif majeur du test de performance est de mesurer la rapidité de chargement


et/ou d'exécution d'une application. Les autres types de tests cités sont similaires mais
mettent l'accent sur le contexte dans lequel se trouve l'application (charge d'utilisateurs,
données d'entrée erronées...) Pour y voir plus clair, nous vous conseillons cet article sur
la différence entre les tests de performance, de charge et de stress.

Vous n'avez pas trouvé cette réponse.

La qualité est définie comme...

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

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.

Vous n'avez pas trouvé cette réponse.

Cochez la formulation juste.

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.

Vous n'avez pas trouvé cette réponse.

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

Les rapports d'incident visent à améliorer la qualité du produit et les processus de


développement et de test. Il ne s'agit pas de pointer du doigt le 'coupable' du bug. Voir
1.5.1.

Vous n'avez pas trouvé cette réponse.

Dans quel ordre se déroulent en principe les différents niveaux de tests ?

1. Tests de composants, tests d'intégration, tests système, tests d'acceptation


2. Tests de composants, tests système, tests d'acceptation, tests d'intégration
3. Tests de composants, tests d'acceptation, tests système, tests d'intégration
4. Tests de composants, tests d'acceptation, tests d'intégration, tests système

Solution

Voir 2.2.

Vous n'avez pas trouvé cette réponse.

L'agilité s'oppose-t-elle au test ?

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.

Vous n'avez pas trouvé cette réponse.


Quand faut-il commencer à tester ?

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

Il est possible de détecter des défauts avant même le début du développement. La


documentation, qui peut être lacunaire, peu claire ou contradictoire, est un objet de test
en tant que tel. Voir chapitre 1.4.2, paragraphe 'Analyse de test'.

Vous n'avez pas trouvé cette réponse.


05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest

 Hey, on recrute ! Dépose ton CV ici

Test ISTQB Foundation en


ligne
1 - LEQUEL DES 4 ÉLÉMENTS SUIVANTS NE FAIT PAS PARTIE DES 7 PRINCIPES GÉNÉRAUX DU TEST LOGICIEL ?

 1. L’illusion d’absence de défaillance


 2. Le regroupement des défauts
 3. Les tests montrent la présence de défauts
 4. Tester tôt

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é

3 - QUEL TYPE DE TEST NE VONT TYPIQUEMENT PAS RÉALISER LES DÉVELOPPEURS ?

 1. Les tests de composants


 2. Les tests d’intégration
 3. Les tests système
 4. Les tests d’acceptation
 Temps restant : 29 min 49 sec Version anglaise 
https://hightest.nc/ressources/test-istqb-2.php 1/6
05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest

4 - QUELLE PRATIQUE DE DÉVELOPPEMENT CONSISTE À ÉCRIRE EN PREMIER LES TESTS UNITAIRES ?

 1. BDD
 2. TDD
 3. ATDD
 4. Scrum

5 - EN PROJET « EN V », QUELS TESTS SONT TYPIQUEMENT JOUÉS EN REGARD DE LA PHASE DE SPÉCIFICATION ?

 1. Les tests d’acceptation


 2. Les tests système
 3. Les tests d’intégration
 4. Les tests de régression

6 - QUELS TESTS NE PEUVENT PAS ÊTRE JOUÉS EN « BOÎTE NOIRE » ?

 1. Les tests d’utilisabilité


 2. Les tests d’acceptation
 3. Les tests de portabilité
 4. Les tests unitaires

7 - LEQUEL DES OBJECTIFS SUIVANTS N’EST TYPIQUEMENT PAS POURSUIVI PAR LES TESTS D’ACCEPTATION ?

 1. S’assurer que le produit est conforme aux besoins des utilisateurs


 2. S’assurer que le produit respecte les exigences contractuelles
 3. S’assurer que l’équipe n’a pas souffert d’illusion d’absence d’erreur
 4. S’assurer que le produit ne comporte aucune régression

 Temps restant : 29 min 49 sec Version anglaise 


https://hightest.nc/ressources/test-istqb-2.php 2/6
05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest

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’erreur est dans le fait d’avoir écrit « 1976 » au lieu de « 1967 »


 2. L’erreur est le fait que le code contiennent la mauvaise date
 3. L’erreur est que la moulinette ait supprimé des documents de 1976
 4. Le récit ne permet pas de connaître l’erreur, seulement le défaut et la défaillance

9 - QU’EST-CE QU’UNE BASE DE TESTS ?

 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

10 - EST-IL POSSIBLE DE TESTER AVANT MÊME QUE LE DÉVELOPPEMENT N’AIT COMMENCÉ ?

 1. Oui, c’est ce qu’on appelle le shift-right


 2. Oui, en effectuant des tests dynamiques sur les exigences
 3. Oui, en établissant des partitions d’équivalences sur le cahier des charges
 4. Oui, en réalisant une revue statique des spécifications

11 - LEQUEL DES FACTEURS DE SUCCÈS SUIVANTS N’EST PAS COMMUN À TOUTES LES PRATIQUES DE REVUE ?

 1. Chaque revue a des objectifs prédéfinis et clairs


 2. Du temps alloué aux activités de revue est prévu dans les plannings des projets
 3. Les
 Temps étapes de la29revue
restant : sont
min 49 formalisées et celle-ci est correctement documentée
sec Version anglaise 
https://hightest.nc/ressources/test-istqb-2.php 3/6
05/01/2023 19:18 Test ISTQB en ligne, niveau Fondation - Hightest

 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 ?

 1. Une fonction contient une boucle infinie


 2. Une variable est initialisée mais jamais utilisée, ce qui peut provoquer une certaine confusion
 3. Au-delà de 50 utilisateurs simultanés, les temps de réponse sont trop élevés
 4. Un mot de passe est stocké en clair

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 ?

 1. Une partition d’équivalences


 2. Un diagramme d’états et de transitions
 3. Une analyse des valeurs limites
 4. Une table de décisions

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 ?

 1. Les tests d’utilisabilité


 2. L’estimation d’erreur
 3. Les tests exploratoires
 4. Les tests basés sur les checklists

16 - LAQUELLE DES AFFIRMATIONS SUIVANTES EST VRAIE ?

 1. La stratégie de test découle du plan de test maître


 2. Le plan de test de niveau fournit une description générale du processus de test, généralement au
niveau du produit ou de l'organisation
 3. Un plan de test détermine le périmètre, les objectifs et les risques des tests
 4. Une stratégie de test permet d’élaborer une politique de tests

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. Appliquer le principe « Tester tôt »


 2. Réaliser davantage d’alpha et de bêta tests
 3. Réaliser davantage de tests de fiabilité
 4. Réaliser davantage de tests de portabilité

18 - LAQUELLE DE CES AFFIRMATIONS SUR L’AUTOMATISATION DES TESTS EST FAUSSE ?

 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

19 - QUEL ÉLÉMENT NE CONTIENT PAS, TYPIQUEMENT, UN RAPPORT DE DÉFAUT ?

 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É !

 Temps restant : 29 min 49 sec Version anglaise 


https://hightest.nc/ressources/test-istqb-2.php 6/6
Résultats du test en ligne - Hightest
Vous avez bien répondu à 8 question(s) sur 20, soit 40 % de réussite. Il faudrait monter
jusqu'à 65 %. Courage !

Lequel des 4 éléments suivants ne fait pas partie des 7 principes généraux du
test logiciel ?

1. L’illusion d’absence de défaillance


2. Le regroupement des défauts
3. Les tests montrent la présence de défauts
4. Tester tôt

Solution

Voir partie 1.3.

Vous n'avez pas trouvé cette réponse.

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é

Solution

Voir ce très bon article de la Taverne du Testeur.

Vous n'avez pas trouvé cette réponse.

Quel type de test ne vont typiquement pas réaliser les développeurs ?


1. Les tests de composants
2. Les tests d’intégration
3. Les tests système
4. Les tests d’acceptation

Solution

Voir 2.2.

Vous avez trouvé la bonne réponse !

Quelle pratique de développement consiste à écrire en premier les tests unitaires


?

1. BDD
2. TDD
3. ATDD
4. Scrum

Solution

Voir 2.2.1.

Vous avez trouvé la bonne réponse !

En projet « en V », quels tests sont typiquement joués en regard de la phase de


spécification ?

1. Les tests d’acceptation


2. Les tests système
3. Les tests d’intégration
4. Les tests de régression
Solution

Voir 2.1.1.

Vous avez trouvé la bonne réponse !

Quels tests ne peuvent pas être joués en « boîte noire » ?

1. Les tests d’utilisabilité


2. Les tests d’acceptation
3. Les tests de portabilité
4. Les tests unitaires

Solution

Voir 2.2.1.

Vous n'avez pas trouvé cette réponse.

Lequel des objectifs suivants n’est typiquement pas poursuivi par les tests
d’acceptation ?

1. S’assurer que le produit est conforme aux besoins des utilisateurs


2. S’assurer que le produit respecte les exigences contractuelles
3. S’assurer que l’équipe n’a pas souffert d’illusion d’absence d’erreur
4. S’assurer que le produit ne comporte aucune régression

Solution

Voir 2.2.4.

Vous n'avez pas trouvé cette réponse.


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’erreur est dans le fait d’avoir écrit « 1976 » au lieu de « 1967 »


2. L’erreur est le fait que le code contiennent la mauvaise date
3. L’erreur est que la moulinette ait supprimé des documents de 1976
4. Le récit ne permet pas de connaître l’erreur, seulement le défaut et la défaillance

Solution

Voir 1.2.3.

Vous n'avez pas trouvé cette réponse.

Qu’est-ce qu’une base de tests ?

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

Solution

Voir le lexique de l'ISTQB.

Vous n'avez pas trouvé cette réponse.


Est-il possible de tester avant même que le développement n’ait commencé ?

1. Oui, c’est ce qu’on appelle le shift-right


2. Oui, en effectuant des tests dynamiques sur les exigences
3. Oui, en établissant des partitions d’équivalences sur le cahier des charges
4. Oui, en réalisant une revue statique des spécifications

Solution

Voir 3.1.1.

Vous n'avez pas trouvé cette réponse.

Lequel des facteurs de succès suivants n’est pas commun à toutes les pratiques
de revue ?

1. Chaque revue a des objectifs prédéfinis et clairs


2. Du temps alloué aux activités de revue est prévu dans les plannings des projets
3. Les étapes de la revue sont formalisées et celle-ci est correctement
documentée
4. La revue est menée dans une atmosphère de confiance ; les résultats ne sont pas
utilisés pour évaluer les participants

Solution

Voir 3.2.3.

Vous n'avez pas trouvé cette réponse.

Lequel des problèmes suivants ne peut pas être détecté lors d’une revue statique
?

1. Une fonction contient une boucle infinie


2. Une variable est initialisée mais jamais utilisée, ce qui peut provoquer une certaine
confusion
3. Au-delà de 50 utilisateurs simultanés, les temps de réponse sont trop élevés
4. Un mot de passe est stocké en clair

Solution

Pour tester l'option 3, des tests dynamiques sont nécessaires.

Vous avez trouvé la bonne réponse !

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 ?

1. Une partition d’équivalences


2. Un diagramme d’états et de transitions
3. Une analyse des valeurs limites
4. Une table de décisions

Solution

Voir 4.2.3

Vous n'avez pas trouvé cette réponse.

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.

Vous n'avez pas trouvé cette réponse.

Laquelle des techniques suivantes n’est pas une technique de test basée sur
l’expérience ?

1. Les tests d’utilisabilité


2. L’estimation d’erreur
3. Les tests exploratoires
4. Les tests basés sur les checklists

Solution

Voir 4.4.

Vous avez trouvé la bonne réponse !

Laquelle des affirmations suivantes est vraie ?

1. La stratégie de test découle du plan de test maître


2. Le plan de test de niveau fournit une description générale du processus de test,
généralement au niveau du produit ou de l'organisation
3. Un plan de test détermine le périmètre, les objectifs et les risques des tests
4. Une stratégie de test permet d’élaborer une politique de tests

Solution

Voir 5.2.1.
Vous avez trouvé la bonne réponse !

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. Appliquer le principe « Tester tôt »


2. Réaliser davantage d’alpha et de bêta tests
3. Réaliser davantage de tests de fiabilité
4. Réaliser davantage de tests de portabilité

Solution

Voir 2.3.5.

Vous avez trouvé la bonne réponse !

Laquelle de ces affirmations sur l’automatisation des tests est fausse ?

1. Les tests automatisés, pour fournir de la valeur ajoutée, doivent réaliser


chaque cas de test en entier
2. Les outils d’automatisation des tests génèrent des informations pour chaque
exécution des tests (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

Solution

Dans certains contextes, il existe de tests semi-automatisés.

Vous n'avez pas trouvé cette réponse.


Quel élément ne contient pas, typiquement, un rapport de défaut ?

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.

Vous avez trouvé la bonne réponse !

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

 Hey, on recrute ! Dépose ton CV ici

Test blanc IREB (CPRE),


niveau Fondamentaux
1 - UNE EXIGENCE EST :

 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

2 - QUELLE PHRASE SUR L’ENGAGEMENT (OU PORTÉE CONTRACTUELLE) EST FAUSSE ?

 1. L’engagement est le degré d’obligation pour satisfaire à l’exigence.


 2. L’engagement est un attribut pouvant impliquer une responsabilité juridique.
 3. Le degré d’engagement est calculé en multipliant l’indice de priorité par l’indice de criticité.
 4. La notation MoSCoW permet d’exprimer le degré requis d’engagement.

3 - QUEL TYPE D’EXIGENCE EST ABSENT DU MODÈLE DE KANO ?

 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

 Temps restant : 29 min 40 sec Version anglaise 


https://hightest.nc/ressources/test-cpre-ireb.php 1/6
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest

 4. Les attributs d’excitation, non prévus par le client, qui répondent à des « besoins inconnus » et
peuvent fournir un avantage concurrentiel significatif

4 - QUELLE EST LA DIFFÉRENCE ENTRE VALIDATION ET VÉRIFICATION ?

 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)

5 - LA TRAÇABILITÉ DES EXIGENCES NE PEUT PAS ÊTRE MISE EN ŒUVRE PAR :

 1. Des références textuelles


 2. Des références implicites
 3. Des hyperliens
 4. Des matrices

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

 Temps restant : 29 min 40 sec Version anglaise 


7 - LES DÉFAUTS RÉSULTANT D’EXIGENCES DE FAIBLE QUALITÉ SONT :
https://hightest.nc/ressources/test-cpre-ireb.php 2/6
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest

 1. Globalement plus coûteux que les autres types de défauts


 2. Globalement d’ordre non-fonctionnel
 3. Généralement peu critiques
 4. Généralement simples à identifier

8 - LEQUEL DE CES ÉLÉMENTS CONTRIBUE À AMÉLIORER LA TESTABILITÉ D’UNE EXIGENCE ?

 1. L’implication des parties prenantes, en particulier des clients


 2. L’analyse des risques
 3. Les éléments en sortie de phase d’élucidation
 4. Le ou les critères d’acceptation

9 - EN ENVIRONNEMENT AGILE, PAR L’INTERMÉDIAIRE DE QUEL MÉCANISME LES EXIGENCES NE SONT PAS
COMMUNIQUÉES ?

 1. Le product backlog


 2. Les user stories
 3. Les daily scrums
 4. Les mockups

10 - QUELLE PHRASE SUR LES DIAGRAMMES DE CAS D’UTILISATION EST FAUSSE ?

 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 »

 Temps restant : 29 min 40 sec Version anglaise 


11 - QUELLE PHRASE SUR LES DIAGRAMMES D’ACTIVITÉ EST FAUSSE ?
https://hightest.nc/ressources/test-cpre-ireb.php 3/6
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest

 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.

13 - UN ÉDITEUR DE LOGICIELS EST EN TRAIN DE DÉVELOPPER UNE APPLICATION DE DOMOTIQUE. UNE


RÉGLEMENTATION SUR LA SÉCURITÉ REQUISE POUR CE TYPE DE LOGICIELS ENTRE EN VIGUEUR. POUR
L’APPLICATION EN DÉVELOPPEMENT, CELA IMPACTE EN PREMIER LIEU :

 1. Le périmètre du système


 2. Les limites du contexte
 3. Les exigences fonctionnelles
 4. Les processus métier

14 - SUR QUOI SE BASE-T-ON POUR PROCÉDER À L’ÉLUCIDATION DES EXIGENCES ?

 1. Sur les limites du système et la gestion des exigences


 2. Sur le périmètre du système et la priorisation des exigences
 3. Sur le contexte du système et les sources d’exigences
 4. Sur les sources du système et le contexte des exigences
 Temps restant : 29 min 40 sec Version anglaise 
https://hightest.nc/ressources/test-cpre-ireb.php 4/6
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest

15 - SELON IREB, LES MODÈLES ONT TROIS CARACTÉRISTIQUES ESSENTIELLES. LAQUELLE N’EN FAIT PAS PARTIE
?

 1. Les modèles représentent la réalité (représentation)


 2. Les modèles réduisent la réalité représentée (abstraction)
 3. Les modèles sont construits pour une utilisation spécifique (pragmatisme)
 4. Les modèles sont maintenables par toutes les parties prenantes (responsabilité partagée)

16 - LEQUEL DE CES ASPECTS NE FAIT PAS PARTIE DES HUIT CRITÈRES DE VALIDATION DU CONTENU D’UNE
EXIGENCE ?

 1. Pas de décisions de conception prématurées


 2. Vérifiabilité
 3. Nécessité
 4. Entente après changement

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

18 - QUELLES SONT LES QUATRE ACTIVITÉS PRINCIPALES DE L’INGÉNIERIE DES EXIGENCES ?

 1. Elucidation – Documentation – Validation/Négociation – Gestion


 2. Elucidation – Analyse – Synthèse – Développement
 3. Elucidation – Délimitation – Complétion/Epuration - Finalisation
 4. Elucidation – Décomposition – Modélisation – Confirmation

 Temps restant : 29 min 40 sec Version anglaise 


https://hightest.nc/ressources/test-cpre-ireb.php 5/6
05/01/2023 19:21 Test IREB en ligne (CPRE), niveau Fondamentaux - Hightest

19 - SI ON UTILISE LA MATRICE DE PRIORITÉS DE KARL WIEGERS (1999), COMMENT CALCULE-T-ON L’INDICE DE


PRIORITÉ D’UNE EXIGENCE ?

 1. Priorité = Valeur en % / Coût en % * coefficient du coût / Risque en % * coefficient du risque


 2. Priorité = Valeur en % / (Coût en % * coefficient du coût + Risque en % * coefficient du risque)
 3. Priorité = Valeur en % / Coût en % * coefficient du coût * Risque en % * coefficient du risque
 4. Priorité = Valeur en % * Coût en % * coefficient du coût * Risque en % * coefficient du risque

20 - SELON IREB, IL EXISTE TROIS SORTES DE CHANGEMENTS DANS LES EXIGENCES. LEQUEL N’EN FAIT PAS
PARTIE ?

 1. Les changements correctifs


 2. Les adaptations
 3. Les changements exceptionnels
 4. Les changements expérimentaux

TERMINÉ !

 Temps restant : 29 min 40 sec Version anglaise 


https://hightest.nc/ressources/test-cpre-ireb.php 6/6
Résultats du test en ligne - Hightest
Vous avez bien répondu à 6 question(s) sur 20, soit 30 % de réussite. Il faudrait monter
jusqu'à 65 %. Courage !

Une exigence est :

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.

Vous n'avez pas trouvé cette réponse.

Quelle phrase sur l’engagement (ou portée contractuelle) est fausse ?

1. L’engagement est le degré d’obligation pour satisfaire à l’exigence.


2. L’engagement est un attribut pouvant impliquer une responsabilité juridique.
3. Le degré d’engagement est calculé en multipliant l’indice de priorité par l’indice
de criticité.
4. La notation MoSCoW permet d’exprimer le degré requis d’engagement.

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).

Vous n'avez pas trouvé cette réponse.


Quel type d’exigence est absent du modèle de Kano ?

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

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.

Vous avez trouvé la bonne réponse !

Quelle est la différence entre validation et vérification ?

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)

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.

Vous avez trouvé la bonne réponse !


La traçabilité des exigences ne peut pas être mise en œuvre par :

1. Des références textuelles


2. Des références implicites
3. Des hyperliens
4. Des matrices

Solution

La traçabilité des exigences permet notamment d'analyser les impacts, la couverture et


les coûts. Leur traçabilité doit être mise en œuvre de manière claire et systématique.
Cet aspect est détaillé dans l'UE 8.4 du syllabus IREB de niveau Fondamentaux.

Vous n'avez pas trouvé cette réponse.

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

Solution

Les prototypes horizontaux, verticaux et de scénario sont les 3 types de prototypes


définis par Jakob Nielsen en 1993 dans Usability Engineering. Ils ne sont pas cités tels
quels dans le syllabus IREB de niveau Fondamentaux, mais sont utiles à connaître
dans le sens où le prototypage est présenté comme une technique d'élucidation et de
validation des exigences (UE 3.3 et 7.5).

Vous n'avez pas trouvé cette réponse.


Les défauts résultant d’exigences de faible qualité sont :

1. Globalement plus coûteux que les autres types de défauts


2. Globalement d’ordre non-fonctionnel
3. Généralement peu critiques
4. Généralement simples à identifier

Solution

Cet aspect est évoqué dès l'UE 1 du syllabus IREB de niveau Fondamentaux.

Vous n'avez pas trouvé cette réponse.

Lequel de ces éléments contribue à améliorer la testabilité d’une exigence ?

1. L’implication des parties prenantes, en particulier des clients


2. L’analyse des risques
3. Les éléments en sortie de phase d’élucidation
4. Le ou les critères d’acceptation

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.

Vous n'avez pas trouvé cette réponse.

En environnement agile, par l’intermédiaire de quel mécanisme les exigences ne


sont pas communiquées ?

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.

Vous n'avez pas trouvé cette réponse.

Quelle phrase sur les diagrammes de cas d’utilisation est fausse ?

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 ».

Vous n'avez pas trouvé cette réponse.

Quelle phrase sur les diagrammes d’activité est fausse ?

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.

Vous n'avez pas trouvé cette réponse.

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.

Solution

Dans un diagramme d'état-transition UML, la vision globale du système n'apparaît pas ;


on ne représente qu'un seul élément du système indépendamment de son
environnement.

Vous n'avez pas trouvé cette réponse.

Un éditeur de logiciels est en train de développer une application de domotique.


Une réglementation sur la sécurité requise pour ce type de logiciels entre en
vigueur. Pour l’application en développement, cela impacte en premier lieu :

1. Le périmètre du système
2. Les limites du contexte
3. Les exigences fonctionnelles
4. Les processus métier
Solution

Les notions de périmètre du système et de limites du contexte sont expliquées dans


l'UE 2 du syllabus IREB de niveau Fondamentaux.

Vous n'avez pas trouvé cette réponse.

Sur quoi se base-t-on pour procéder à l’élucidation des exigences ?

1. Sur les limites du système et la gestion des exigences


2. Sur le périmètre du système et la priorisation des exigences
3. Sur le contexte du système et les sources d’exigences
4. Sur les sources du système et le contexte des exigences

Solution

Ces notions sont expliquées dans l'UE 3.1 du syllabus IREB de niveau Fondamentaux.

Vous n'avez pas trouvé cette réponse.

Selon IREB, les modèles ont trois caractéristiques essentielles. Laquelle n’en fait
pas partie ?

1. Les modèles représentent la réalité (représentation)


2. Les modèles réduisent la réalité représentée (abstraction)
3. Les modèles sont construits pour une utilisation spécifique (pragmatisme)
4. Les modèles sont maintenables par toutes les parties prenantes
(responsabilité partagée)

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 ?

1. Pas de décisions de conception prématurées


2. Vérifiabilité
3. Nécessité
4. Entente après changement

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.

Vous avez trouvé la bonne réponse !

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.

Vous n'avez pas trouvé cette réponse.


Quelles sont les quatre activités principales de l’ingénierie des exigences ?

1. Elucidation – Documentation – Validation/Négociation – Gestion


2. Elucidation – Analyse – Synthèse – Développement
3. Elucidation – Délimitation – Complétion/Epuration - Finalisation
4. Elucidation – Décomposition – Modélisation – Confirmation

Solution

Ces quatre activités sont indiquées dans l'UE 1 du syllabus IREB de niveau
Fondamentaux.

Vous avez trouvé la bonne réponse !

Si on utilise la matrice de priorités de Karl Wiegers (1999), comment calcule-t-on


l’indice de priorité d’une exigence ?

1. Priorité = Valeur en % / Coût en % * coefficient du coût / Risque en % * coefficient du


risque
2. Priorité = Valeur en % / (Coût en % * coefficient du coût + Risque en % *
coefficient du risque)
3. Priorité = Valeur en % / Coût en % * coefficient du coût * Risque en % * coefficient du
risque
4. Priorité = Valeur en % * Coût en % * coefficient du coût * Risque en % * coefficient du
risque

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.

Vous avez trouvé la bonne réponse !


Selon IREB, il existe trois sortes de changements dans les exigences. Lequel
n’en fait pas partie ?

1. Les changements correctifs


2. Les adaptations
3. Les changements exceptionnels
4. Les changements expérimentaux

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

 Hey, on recrute ! Dépose ton CV ici

Test A4Q Testeur Selenium


Certifié
1 - 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.

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 ?

 1. La connaissance du contexte fonctionnel


 2. La résilience en cas de comportement non anticipé du système à tester
 3. La capacité à adapter ses actions en fonction du comportement constaté sur l'application à tester
 4. La capacité d'analyser les comportements inattendus du système à tester

3 - LEQUEL DES ÉLÉMENTS SUIVANTS NE FAIT PAS PARTIE DES FACTEURS DE SUCCÈS DE L'AUTOMATISATION DES
TESTS ?

 Temps restant : 29 min 53 sec Version anglaise 


https://hightest.nc/ressources/test-a4q-selenium.php 1/7
05/01/2023 19:23 Test A4Q Testeur Selenium Certifié, niveau Fondation - Hightest

 1. Une architecture et un cadre formalisés


 2. Une formation adaptée
 3. Un plan à long terme aligné sur les besoins de l'entreprise
 4. La garantie que l'interface utilisateur ne changera plus

4 - LE DÉVELOPPEMENT DE TESTS FONCTIONNELS DYNAMIQUES AUTOMATISÉS COMPORTE CERTAINS RISQUES.


LEQUEL N'EN FAIT PAS PARTIE ?

 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)

7 - LEQUEL DES 4 OUTILS DE L'ÉCOSYSTÈME SELENIUM EST UN OUTIL DE CAPTURE-REJEU ?

 1. Selenium Standalone Server


 2. Selenium Grid
 3. Selenium WebDriver
 4. Selenium IDE

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 ?

USERNAME OR EMAIL Your username or email


PASSWORD Your password
REMEMBER ME

<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

13 - COMMENT FERME-T-ON UN NAVIGATEUR AVEC SELENIUM WEBDRIVER (PYTHON) ?

 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 ?

 1. Le fait qu'un élément soit cliquable


 2. Le fait qu'un élément soit visible
 3. Le fait qu'un élément soit en mouvement (par exemple, un carrousel d'images est en mouvement)
 4. Le fait qu'un élément soit présent dans le DOM (sans forcément être visible par l'utilisateur)

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()

18 - IL EXISTE PLUSIEURS MANIÈRES DE RENDRE UN PROJET DE TESTS AUTOMATISÉS PLUS MAINTENABLE.


LAQUELLE N'EN FAIT PAS PARTIE ?

 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.

19 - POUR QUELLE RAISON LA MÉTHODE SLEEP() EST-ELLE DÉCONSEILLÉE ?

 1. Cette méthode n'existe tout simplement pas.


 2. Cette méthode existe toujours, mais elle a été dépréciée au profit de la méthode drowse(). La
méthode sleep() en effet produisait une attente incompressible, alors que la méthode drowse() vérifie
dynamiquement si la condition attendue est remplie.
 3. Ce type de mécanisme d'attente considère le temps de réponse dans le pire des cas. Comme cela
ne se produit pas souvent, la plus grande partie de ce temps d'attente est donc perdue.
 4. La méthode sleep() n'est pas déconseillée.

20 - QUELLE AFFIRMATION SUR LES PAGE OBJECTS EST FAUSSE ?

 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É !

 Temps restant : 29 min 53 sec Version anglaise 


https://hightest.nc/ressources/test-a4q-selenium.php 7/7
Résultats du test en ligne - Hightest
Vous avez bien répondu à 6 question(s) sur 20, soit 30 % de réussite. Il faudrait monter
jusqu'à 65 %. Courage !

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.

Vous avez trouvé la bonne réponse !

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 ?

1. La connaissance du contexte fonctionnel


2. La résilience en cas de comportement non anticipé du système à tester
3. La capacité à adapter ses actions en fonction du comportement constaté sur
l'application à tester
4. La capacité d'analyser les comportements inattendus du système à tester

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.

Vous n'avez pas trouvé cette réponse.


Lequel des éléments suivants ne fait pas partie des facteurs de succès de
l'automatisation des tests ?

1. Une architecture et un cadre formalisés


2. Une formation adaptée
3. Un plan à long terme aligné sur les besoins de l'entreprise
4. La garantie que l'interface utilisateur ne changera plus

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.

Vous n'avez pas trouvé cette réponse.

Le développement de tests fonctionnels dynamiques automatisés comporte


certains risques. Lequel n'en fait pas partie ?

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.

Vous n'avez pas trouvé cette réponse.


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.

Solution

Voir 1.5.

Vous n'avez pas trouvé cette réponse.

Plusieurs métriques sont proposées pour un petit projet d'automatisation des


tests. Laquelle n'en fait pas partie ?

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.

Vous n'avez pas trouvé cette réponse.

Lequel des 4 outils de l'écosystème Selenium est un outil de capture-rejeu ?

1. Selenium Standalone Server


2. Selenium Grid
3. Selenium WebDriver
4. Selenium IDE

Solution

Voir 1.7.

Vous n'avez pas trouvé cette réponse.

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.

Vous n'avez pas trouvé cette réponse.

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.

Vous avez trouvé la bonne réponse !


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 permettant de récupérer l'adresse
e-mail de l'utilisateur dont l'identifiant est Nicolas ?

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.

Vous avez trouvé la bonne réponse !

Voir 2.3. La syntaxe correcte aurait dû être [placeholder='Your password'].

Vous n'avez pas trouvé cette réponse.

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.

Vous avez trouvé la bonne réponse !

Comment ferme-t-on un navigateur avec Selenium WebDriver (Python) ?


1. driver.close()
2. driver.dismiss()
3. driver.kill()
4. driver.quit()

Solution

Voir 3.2.

Vous n'avez pas trouvé cette réponse.

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

Voir 3.3. La méthode find_elements_by_class_name ne retourne pas un élément, mais


un tableau d'éléments.

Vous n'avez pas trouvé cette réponse.

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.

Vous n'avez pas trouvé cette réponse.

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 ?

1. Le fait qu'un élément soit cliquable


2. Le fait qu'un élément soit visible
3. Le fait qu'un élément soit en mouvement (par exemple, un carrousel d'images
est en mouvement)
4. Le fait qu'un élément soit présent dans le DOM (sans forcément être visible par
l'utilisateur)

Solution

Voir 3.5.

Vous n'avez pas trouvé cette réponse.

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.

Vous n'avez pas trouvé cette réponse.


Il existe plusieurs manières de rendre un projet de tests automatisés plus
maintenable. Laquelle n'en fait pas partie ?

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 et sélecteurs CSS.
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.

Solution

Voir 4.1.

Vous n'avez pas trouvé cette réponse.

Pour quelle raison la méthode sleep() est-elle déconseillée ?

1. Cette méthode n'existe tout simplement pas.


2. Cette méthode existe toujours, mais elle a été dépréciée au profit de la méthode
drowse(). La méthode sleep() en effet produisait une attente incompressible, alors que
la méthode drowse() vérifie dynamiquement si la condition attendue est remplie.
3. Ce type de mécanisme d'attente considère le temps de réponse dans le pire
des cas. Comme cela ne se produit pas souvent, la plus grande partie de ce
temps d'attente est donc perdue.
4. La méthode sleep() n'est pas déconseillée.

Solution

Voir 4.2.

Vous avez trouvé la bonne réponse !


Quelle affirmation sur les Page Objects est fausse ?

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

 Hey, on recrute ! Dépose ton CV ici

Quiz Selenium & Java


1 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC STRING GETNOMARTICLE(){


2 RETURN DRIVER.FINDELEMENT(BY.ID("NOMARTICLE"));
3 }

QUESTION-1.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. L'id est mal formé.


 2. Le type de la valeur de retour est incohérent.
 3. La variable 'driver' n'a pas été déclarée.
 4. La méthode findElement() n'existe pas (findElements() en revanche existe).

2 - CETTE ERREUR EST SURVENUE AU MOMENT DE CLIQUER SUR UN BOUTON. QUE SIGNIFIE-T-ELLE ?

1 EXCEPTION IN THREAD "MAIN" ORG.OPENQA.SELENIUM.ELEMENTNOTINTERACTABLEEXCEPTION

QUESTION-2.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC VOID VERIFIERNOMBREARTICLESPANIER(INT NOMBREARTICLESATTENDUS) {


2 ASSERT.ASSERTTRUE(DRIVER.FINDELEMENT(BY.ID("NBARTICLESPANIER")).GETTEXT(), NOMBREARTICLESATTENDUS);
 Temps restant : 29 min 56 sec Version anglaise 
https://hightest.nc/ressources/test-selenium-java.php 1/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

3 }

QUESTION-3.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. La variable 'nombreArticlesAttendus' a un nom trop long.


 2. La comparaison porte sur deux type différents.
 3. Il manque un argument pour pouvoir correctement appeler la méthode assertTrue().
 4. Le type de retour de la méthode est incohérent.

4 - QUE SE PASSERA-T-IL SI ON APPELLE CETTE MÉTHODE AVEC 3 EN ARGUMENT ?

1 PROTECTED VOID SLEEP(INT SECONDS) {


2 TRY {
3 THREAD.SLEEP(SECONDS);
4 } CATCH (INTERRUPTEDEXCEPTION E) {
5 E.PRINTSTACKTRACE();
6 }
7 }

QUESTION-4.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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.

5 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC STRING GETTITREPAGE(){


2 STRING TITREPAGE = DRIVER.GET();
3 }

QUESTION-5.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. La méthode getTitle() n'existe pas.


 2. '=' devrait être remplacé par '=='.
 3. getTitrePage() devrait avoir un argument.
 4. La méthode ne retourne aucune valeur.
 Temps restant : 29 min 56 sec Version anglaise 
https://hightest.nc/ressources/test-selenium-java.php 2/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

6 - OÙ EST LE PROBLÈME ICI ?

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 }

QUESTION-6.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. Dans le constructeur de la classe.


 2. Dans la méthode publique.
 3. Dans la String privée.
 4. Il n'y a pas de problème.

7 - A QUEL PROBLÈME S'EXPOSE-T-ON ICI ?

1 PUBLIC VOID VERIFIERNOMARTICLE(){


2 VERIFIERNOMARTICLE();
3 }
4
5 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){
6 ASSERT.ASSERTEQUALS(DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")), NOMARTICLEATTENDU);
7 }

QUESTION-7.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW


 Temps restant : 29 min 56 sec Version anglaise 
https://hightest.nc/ressources/test-selenium-java.php 3/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

 1. A une erreur de type StackOverflowError.


 2. A une erreur de type InvalidSelectorException.
 3. A une erreur de type ConnectionClosedException.
 4. A une erreur de type InvalidArgumentException.

8 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){


2 ASSERT.ASSERTEQUALS(DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT() == NOMARTICLEATTENDU);
3 }

QUESTION-8.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. '==' devrait être remplacé par '='.


 2. '==' devrait être remplacé par '==='.
 3. Le nombre d'arguments de la méthode appelée n'est pas respecté.
 4. Il manque une parenthèse.

9 - POURQUOI CE SÉLECTEUR NE FONCTIONNERA PAS ? (CONNAÎTRE NOTRE CLASSE SELECTEUR N'A PAS
D'IMPORTANCE ICI.)

1 PRIVATE FINAL SELECTEUR INPUT_USERNAME = NEW SELECTEUR("LE CHAMP DE SAISIE DE L'IDENTIFIANT",


BY.ID("//INPUT[ID='INPUT-LOGIN-USERNAME']"));

QUESTION-9.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. Parce qu'il est saisi sur une ligne au lieu de deux.


 2. Parce que les guillemets simples ne sont pas échappés.
 3. Parce que l'id saisi est un xPath.
 4. Parce que sa visibilité est 'private'.

10 - QUEL EST LE PRINCIPAL PROBLÈME ICI ?

1 PUBLIC VOID GETNOMARTICLE(){


2 RETURN DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
 Temps restant : 29 min 56 sec Version anglaise 
https://hightest.nc/ressources/test-selenium-java.php 4/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

3 }

QUESTION-10.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. Il manque une parenthèse.


 2. La méthode retourne une valeur, mais la déclaration annonce qu'elle ne va rien retourner.
 3. La méthode getNomArticle() devrait avoir un argument ou plus.
 4. La méthode n'est appelée nulle part, ce qui signifie qu'elle représente du code mort, qui ne sera pas
maintenu ou bien sera inutilement maintenu.

11 - POURQUOI CETTE ERREUR S'EST PRODUITE ?

1 ORG.OPENQA.SELENIUM.INVALIDSELECTOREXCEPTION: COMPOUND CLASS NAMES ARE NOT SUPPORTED

QUESTION-11.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. Parce que l'élément n'a pas été trouvé sur la page.


 2. Parce que le nom de la classe contenant les méthodes de tests était déjà utilisé ailleurs.
 3. Parce que le sélecteur était de type className et contenait plusieurs classes séparées par des
espaces.
 4. Parce que le WebDriver ne s'est pas correctement initialisé.

12 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC INT GETNOMBREARTICLESPANIER(){


2 RETURN DRIVER.FINDELEMENT(BY.ID("NBARTICLESPANIER")).GETTEXT();
3 }

QUESTION-12.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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.

 Temps restant : 29 min 56 sec Version anglaise 


13 - QUEL EST LE PROBLÈME ICI ?
https://hightest.nc/ressources/test-selenium-java.php 5/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

1 PUBLIC VOID VERIFIERVALEURCHAMPLOGIN(STRING LOGINATTENDU){


2 WEBELEMENT ELEMENT = DRIVER.FINDELEMENT(BY.XPATH("//INPUT[@ID='LOGIN']"));
3 ASSERT.ASSERTEQUALS(ELEMENT.GETTEXT(), LOGINATTENDU);
4 }

QUESTION-13.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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 ?

1 PUBLIC VOID VERIFIERNOMARTICLE(){


2 VERIFIERNOMARTICLE(300);
3 }
4
5 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){
6 ASSERT.ASSERTEQUALS(DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT(), NOMARTICLEATTENDU);
7 }

QUESTION-14.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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().

15 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU, STRING NOMARTICLECONSTATE){


2 STRING NOMARTICLECONSTATE = DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
3 ASSERT.ASSERTEQUALS(NOMARTICLECONSTATE, NOMARTICLEATTENDU);
4 }

 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.

16 - OÙ EST LE PROBLÈME ICI ?

1 PRIVATE BOOLEAN ISMODECONNECTE(){


2 RETURN DRIVER.FINDELEMENTS(BY.XPATH("//DIV[ID='DECONNEXION']")).SIZE() > 0;
3 }

QUESTION-16.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. La méthode ne devrait pas être à la visibilité 'private', mais 'public'.


 2. Le type de la valeur retournée est incohérent.
 3. Dans le xPath (il faudrait remplacer xPath par cssSelector).
 4. Dans le xPath (au niveau de l'attribut).

17 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC CLASS TESTNOMARTICLE {


2
3 @TEST
4 PUBLIC VOID VERIFIERNOMARTICLE(){
5 WEBDRIVERMANAGER.CHROMEDRIVER().SETUP();
6 WEBDRIVER DRIVER = NEW CHROMEDRIVER();
7 DRIVER.GET("HTTPS://TESTEUM.COM/");
8 STRING NOMARTICLECONSTATE = DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
9 ASSERT.ASSERTEQUALS(NOMARTICLECONSTATE, NOMARTICLEATTENDU);
10 }
11 }

QUESTION-17.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 Temps restant : 29 min 56 sec Version anglaise 


https://hightest.nc/ressources/test-selenium-java.php 7/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

 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.

18 - QUEL EST LE PROBLÈME ICI ?

1 PUBLIC VOID VERIFIERDONNEESARTICLE(INT PRIXARTICLE, STRING NOMARTICLE){


2 VERIFIERPRIXARTICLE(PRIXARTICLE);
3 VERIFIERNOMARTICLE(NOMARTICLE);
4 }
5
6 PUBLIC VOID VERIFIERPRIXARTICLE(INT PRIXARTICLE){
7 ASSERT.ASSERTEQUALS(INTEGER.PARSEINT(DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT())),
PRIXARTICLE);
8 }
9
10 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){
11 STRING NOMARTICLECONSTATE = DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
12 ASSERT.ASSERTEQUALS(NOMARTICLECONSTATE, NOMARTICLEATTENDU);
13 }

QUESTION-18.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 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.

19 - POURQUOI CETTE MÉTHODE EST-ELLE RISQUÉE ?

1 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){


2 STRING NOMARTICLECONSTATE = DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
3 ASSERT.ASSERTTRUE(NOMARTICLECONSTATE == NOMARTICLEATTENDU);
4 }

QUESTION-19.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW


 Temps restant : 29 min 56 sec Version anglaise 
https://hightest.nc/ressources/test-selenium-java.php 8/9
05/01/2023 19:25 Quiz Selenium & Java - Hightest

 1. Elle n'est pas risquée.


 2. Parce que == vérifie moins que ===, et il y a donc des chances que deux chaînes de caractères
différentes soient jugées identiques (exemple : casses différentes).
 3. Parce qu'elle peut, dans certains cas, produire une boucle infinie.
 4. Parce que == ne compare pas simplement le contenu des String, mais vérifie que les deux String
sont le même objet.

20 - OÙ EST LE PROBLÈME ICI ?

1 PUBLIC VOID VERIFIERDONNEESARTICLE(INT PRIXARTICLE, STRING NOMARTICLE){


2 VERIFIERPRIXARTICLE(PRIXARTICLE);
3 VERIFIERNOMARTICLE(NOMARTICLE);
4 }
5
6 PUBLIC VOID VERIFIERPRIXARTICLE(INT PRIXARTICLE){
7 ASSERT.ASSERTEQUALS(INTEGER.PARSEINT(DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT()),
PRIXARTICLE)
8 }
9
10 PUBLIC VOID VERIFIERNOMARTICLE(STRING NOMARTICLEATTENDU){
11 STRING NOMARTICLECONSTATE = DRIVER.FINDELEMENT(BY.ID("NOMARTICLE")).GETTEXT();
12 ASSERT.ASSERTEQUALS(NOMARTICLECONSTATE, NOMARTICLEATTENDU);
13 }

QUESTION-20.JAVA HOSTED WITH ❤ BY GITHUB VIEW RAW

 1. Dans la première méthode


 2. Dans la deuxième méthode
 3. Dans la troisième méthode
 4. Il n'y a pas de problème

TERMINÉ !

 Temps restant : 29 min 56 sec Version anglaise 


https://hightest.nc/ressources/test-selenium-java.php 9/9
Résultats du test en ligne - Hightest
Vous avez bien répondu à 5 question(s) sur 20, soit 25 % de réussite. Il faudrait monter
jusqu'à 65 %. Courage !

Quel est le problème ici ?

1. L'id est mal formé.


2. Le type de la valeur de retour est incohérent.
3. La variable 'driver' n'a pas été déclarée.
4. La méthode findElement() n'existe pas (findElements() en revanche existe).

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.

Vous n'avez pas trouvé cette réponse.

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.

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

1. La variable 'nombreArticlesAttendus' a un nom trop long.


2. La comparaison porte sur deux type différents.
3. Il manque un argument pour pouvoir correctement appeler la méthode assertTrue().
4. Le type de retour de la méthode est incohérent.

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().

Vous n'avez pas trouvé cette réponse.

Que se passera-t-il si on appelle cette méthode avec 3 en argument ?

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

Attention aux conversions millisecondes -> secondes.

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

1. La méthode getTitle() n'existe pas.


2. '=' devrait être remplacé par '=='.
3. getTitrePage() devrait avoir un argument.
4. La méthode ne retourne aucune valeur.

Solution

Une correction rapide : return driver.getTitle();

Vous avez trouvé la bonne réponse !

Où est le problème ici ?


1. Dans le constructeur de la classe.
2. Dans la méthode publique.
3. Dans la String privée.
4. Il n'y a pas de problème.

Solution

Le constructeur actuel affecte toujours la String 'codePays' avec la valeur 'FR'.

Vous n'avez pas trouvé cette réponse.

A quel problème s'expose-t-on ici ?

1. A une erreur de type StackOverflowError.


2. A une erreur de type InvalidSelectorException.
3. A une erreur de type ConnectionClosedException.
4. A une erreur de type InvalidArgumentException.

Solution

La première méthode occasionne une boucle infinie !

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

1. '==' devrait être remplacé par '='.


2. '==' devrait être remplacé par '==='.
3. Le nombre d'arguments de la méthode appelée n'est pas respecté.
4. Il manque une parenthèse.

Solution

Actuellement, il n'y a qu'un seul argument, de type booléen. La méthode assertEquals()


doit comparer deux valeurs.

Vous n'avez pas trouvé cette réponse.


Pourquoi ce sélecteur ne fonctionnera pas ? (Connaître notre classe Selecteur n'a
pas d'importance ici.)

1. Parce qu'il est saisi sur une ligne au lieu de deux.


2. Parce que les guillemets simples ne sont pas échappés.
3. Parce que l'id saisi est un xPath.
4. Parce que sa visibilité est 'private'.

Solution

Voir la documentation de l'objet By.

Vous n'avez pas trouvé cette réponse.

Quel est le principal problème ici ?

1. Il manque une parenthèse.


2. La méthode retourne une valeur, mais la déclaration annonce qu'elle ne va rien
retourner.
3. La méthode getNomArticle() devrait avoir un argument ou plus.
4. La méthode n'est appelée nulle part, ce qui signifie qu'elle représente du code mort,
qui ne sera pas maintenu ou bien sera inutilement maintenu.

Solution

Une correction rapide : remplacer 'void' par 'String'.

Vous n'avez pas trouvé cette réponse.

Pourquoi cette erreur s'est produite ?

1. Parce que l'élément n'a pas été trouvé sur la page.


2. Parce que le nom de la classe contenant les méthodes de tests était déjà utilisé
ailleurs.
3. Parce que le sélecteur était de type className et contenait plusieurs classes
séparées par des espaces.
4. Parce que le WebDriver ne s'est pas correctement initialisé.

Solution
Ce fil de discussion propose quelques moyens de contournement.

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

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.

Solution

La déclaration de la méthode annonce qu'elle va retourner un 'int', mais elle retourne


une 'String'. La méthode Integer.parseInt() pourrait être utile.

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

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.

Solution

Pour récupérer le contenu d'un input, il faut utiliser non pas la méthode getText() mais
getAttribute('value').

Vous n'avez pas trouvé cette réponse.

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

Une correction rapide : remplacer 300 par "300".

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

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.

Solution

Une correction rapide : retirer le deuxième argument de la déclaration de la méthode.

Vous avez trouvé la bonne réponse !

Où est le problème ici ?

1. La méthode ne devrait pas être à la visibilité 'private', mais 'public'.


2. Le type de la valeur retournée est incohérent.
3. Dans le xPath (il faudrait remplacer xPath par cssSelector).
4. Dans le xPath (au niveau de l'attribut).

Solution

Voici un exercice pour vous entraîner à l'écriture d'xPath ! :)

Vous avez trouvé la bonne réponse !


Quel est le problème ici ?

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

Besoin d'un récap sur les portées des variables en Java ?

Vous n'avez pas trouvé cette réponse.

Quel est le problème ici ?

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

Ce type d'erreur est simple à corriger mais parfois difficile à trouver.

Vous avez trouvé la bonne réponse !

Pourquoi cette méthode est-elle risquée ?

1. Elle n'est pas risquée.


2. Parce que == vérifie moins que ===, et il y a donc des chances que deux chaînes de
caractères différentes soient jugées identiques (exemple : casses différentes).
3. Parce qu'elle peut, dans certains cas, produire une boucle infinie.
4. Parce que == ne compare pas simplement le contenu des String, mais vérifie
que les deux String sont le même objet.
Solution

Voir ce récapitulatif en ligne.

Vous avez trouvé la bonne réponse !

Où est le problème ici ?

1. Dans la première méthode


2. Dans la deuxième méthode
3. Dans la troisième méthode
4. Il n'y a pas de problème

Solution

Il manquait juste un point virgule !

Vous n'avez pas trouvé cette réponse.


05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject

Online Selenium Quiz – Test Your


Knowledge!

How well do you think you know Selenium WebDriver?

Test your knowledge with this most up to date Selenium quiz!

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

Data Driven Testing (DDT) is a methodology in automated testing to test only


a single set of Test Data.
True False

Select the following true statements:


Confidentialité - Conditions

https://blog.testproject.io/quiz/interview/ 1/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject

webDriver.Quit() - Closes the browser windows


webDriver.Quit() - Calls Dispose()
webDriver.Close() - Closes the focused browser window
webDriver.Close() - Closes all browser windows

WebDriverWait wait = new WebDriverWait(driver, 30);

wait.until(ExpectedConditions.presenceOfElementLocated(by));

The above wait condition is considered an:

Explicit wait
Implicit wait

Which browsers support Selenium IDE ?

Google Chrome
Internet Explorer
Opera
Mozilla Firefox
All of the above

Using Selenium, how can we click on an element at certain coordinates ?

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

Consider the following HTML:

<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' ?

Select all the correct answers.


By.xpath("//div[contains(@class, 'container') or contains(@class, 'title')]");
By.xpath("//div[contains(@class, 'container title')");
By.xpath("//div[contains(@class, 'container') and contains(@class, 'title')]");
By.ClassName("container title");

Click SUBMIT to find out how you scored! Enter your E-


mail address to receive the correct answers via mail.
***Your E-mail address will remain confidential. We will NOT spam, spy and we will
NEVER share your information with any third parties.

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

Trending Forum Topics

Resources

https://blog.testproject.io/quiz/interview/ 4/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject

Subscribe to get our best content in


your inbox
Testing trends & best practices

Step-by-step tutorials & tips

Authentic opinion blogs

Email Address SUBMIT

EASY TEST AUTOMATION

ADVANCED SCRIPTING CAPABILITIES

PROVEN TESTING SOLUTIONS

COMMUNITY

https://blog.testproject.io/quiz/interview/ 5/6
05/01/2023 19:52 Online Selenium Quiz - Test Your Knowledge! - TestProject

BLOG CATEGORIES

COMPANY

© 2022 TestProject. All Right Reserved.


Terms of Service

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:

3° Select the following true statements:

Correct Answer: webDriver.Quit() - Calls Dispose().webDriver.Close() - Closes the focused


browser window

Question:

4° WebDriverWait wait = new WebDriverWait(driver, 30);

wait.until(ExpectedConditions.presenceOfElementLocated(by));

The above wait condition is considered an:

Correct Answer: Explicit wait

Question:

5° Which browsers support Selenium IDE ?

Correct Answer: Mozilla Firefox

Question:

6° Using Selenium, how can we click on an element at certain coordinates ?

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:

8° Consider the following HTML:

Using Selenium WebDriver, how would you select only the element with the 2
classes: 'container' and 'title' ?

Correct Answer: By.xpath("//div[contains(@class, 'container


title')");.By.xpath("//div[contains(@class, 'container') and contains(@class, 'title')]");
05/01/2023 20:07 Selenium Webdriver Interview Questions with Answer

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

Selenium Webdriver Interview Questions


with Answer
- August 31, 2017

1. Selenium doesn't support __________ to write programs (Test Scripts)


a) Java
b) Perl
c) VBScript
d) Python

2. __________ is an Advantage of Selenium WebDriver?


a) Supports Web based Applications only
b) No built-in Result Reporting facility
c) Open Source
d) No IDE

3. In webdriver, which methods navigates to a URL?


a) goToUrl("url")
b) navigate.to("url")
c) getUrl("url")
d) get("url")

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()

6. In webdriver, selectAllOptions() is a valid command.


a) True
b) False

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()

9. Consider the following code snippet


WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(by));
This is an example of an implicit wait.
a) True
b) False

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()

14. Which of the following is used to toggle a checkbox in a web form?


a) Element.toggle()
b) Element.click()
c) Element.set()
d) Element.select()

15. Which of the following will terminate the test when the check fails
a) Verify
b) Assert

16. How to switch between windows


a).switchto().window(Integer)
b).switchto().window(string)
c).switchto().window(Array)
d) .switchto().window(array list)

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

c) Alert alert = driver.switchalert();


String message = alert.getText();

18. Identify the Invalid Xpath for Submit button


a) //*[@class=’submit’]
b) //div[contain(@class,’submit’)]
c) //div[@class=’submit’]
d) //div[contains(@class,’submit’)]

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

20. In webdriver, which method closes the open browser?


a) quit()
b) terminate()
c) shutdown()
d) close()

21. What is the output of the following statement?


<div> <a id=’name’>Name 1 </a>
<a id=’name’>Name 2 </a></div>
driver.findElement(By.cssSelector(“#name”));

a) Output is Name 1
b) Output is Name 2
c) CSS selector syntax is incorrect

22. Select which are NOT the type of the locaters.


a) ID
b) Name
c) Password
d) Link Text

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

24. Identify the correct statement about Implicit Wait-


a) An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying
to find an element or elements if they are not immediately available.
b) The default setting is 0.
c) Once set, the implicit wait is set for the life of the WebDriver object instance.
d) An implicit wait is the code you define to wait for a certain condition to occur before
proceeding further in the code.

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();

27. Identify Incorrect URL for Console grid


a) http://localhost:portno
b.http://localhost:portno/grid/console
c.https://localhost:portno/grid/console

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()

30. Consider the following html snippet


      • Firefox
      • Google Chrome
      • Internet Explorer
      • Opera
      • Safari
Which CSS selector is a valid statement to select Opera?
a) css = li.contains("Opera")
b) css = ul.li(4)
c) css = ul > li:nth-of-type(4)
d) css = ul > li:nth-of-type(3)
e) css = ul.li:nth-child(4)

31. The following codes both print the same value


        System.out.println(driver.getTitle());
        System.out.println(driver.findElement(By.tagName(“title”)).getText())
a) True
b) False

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

36. What is the use of Desired Capabilities


a) It is used for Selenium Grid
b) It gives facility to set the properties of browser.
c) It is used to execute multiple test cases on multiple Systems with different browser with
Different version and Different Operating System.
d) All of the above

37. A code snippet related to Fluent wait

   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

38. Selenium Framework Component that supports Listener


a) Webdriver
b) TestNG
c) Junit
d) Selenium GRID

39. Identify the Invalid Syntax for Java script executor


a) WebDriver driver = new ChromeDriver();
     if (driver instanceof JavascriptExecutor) {
     ((JavascriptExecutor) driver).executeScript("alert('hello world');");
  }
b) JavascriptExecutor js = new JavascriptExecutor(driver);
    js.executeScript("arguments[0].click();", element);
c) JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("arguments[0].click();", element);

40. Identify Invalid Syntax for refreshing the browser


a) driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
b) driver.refresh();
c) driver.get(driver.getCurrentUrl());
d) driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");

41. Consider the following HTML code snippet


1 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

a) The above statement returns 1


b) The above statement returns 3
c) The xpath query is incorrect
d) webdriver statement is incorrect

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()

43. Selenium is compatible with


a) CSS1.0 and CSS 2.0,
b) CSS1.0, CSS 2.0, and CSS 3.0 selectors.
c) CSS 2.0, and CSS 3.0 selectors.
d) CSS1.0, CSS 2.0, CSS 3.0 and CSS 4.0 selectors.

44. Which process use the JavaScript to find an element?


a) By DOM query
b) BY XPath query
c) BY CSS sector
d) All of these

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

autofocus=”autofocus” value=”” name=”q” />

Identify the invalid Xpath from the following options.

a) //input[starts-with(@id, ‘fk-top-search-box’) and contains(@class, ‘fk-font-13)]


b) //input[@id=’fk-top-search-box’]
c) //input[starts-with(@class, ”search-bar-text”)]
d) //input[starts-with(@id, ‘top-search-box’) and contains(@class, ‘font-13’)]

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()

49. The // tells the query that


a) It needs to stop at the first element that it finds.
b) This is comment
c) The path of the file or folder
d) All of these

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

Answers for the above questions,

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

answer choice interview questions RC Selenium Selenium Grid

Selenium webdriver wedriver

Popular posts from this blog

Selenium IDE Interview Questions with Answer


- August 31, 2017

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

DLL to Jar file conversion


- November 24, 2015

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

Theme images by badins

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

Chennai, Tamil Nadu, India

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

Selenium Test Automation


Saturday, 18 April 2015 About Me

Ramesh Kudikala
Selenium Ques $ Ans -1
View my complete profile

1) What is Selenium and what is composed of?


Blog Archive
Selenium is a suite of tools for automated web testing.  It is composed of ▼ 
▼  2015 (15)
▼ 
▼  April (15)
·          Selenium IDE (Integrated Development Environment) :  It is a tool for recording and playing back. 
Selenium Quiz - 3
It is a firefox plugin Selenium Quiz - 2
·          WebDriver and RC:  It provide the APIs for a variety of languages like Java, .NET, PHP, etc. With most of Selenium Quiz - 1
the browsers Webdriver and RC works. Java Questions and anwsers

·          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?

For web based application testing selenium can be used

The test types can be supported are

a)      Functional

b)      Regression

For post release validation with continuous integration automation tool could be used

a)      Jenkins

b)      Hudson

c)       Quick Build

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.

7) Explain the difference between single and double slash in X-path?

Single slash ‘/ ’

·          Single slash ( / ) start selection from the document node


·          It allows you to create ‘absolute’ path expressions

Double Slash ‘// ’

·          Double slash ( // ) start selection matching anywhere in the document


·          It enables to create ‘relative’ path expressions
8) List out the technical challenges with Selenium?

Technical challenges with Selenium are

·          Selenium supports only web based applications


·          It does not support the Bitmap comparison
·          For any reporting related capabilities have to depend on third party tools
·          No vendor support for tool compared to commercial tools like HP UFT
·          As there is no object repository concept in Selenium, maintainability of objects becomes difficult
9) What is the difference between type keys and type commands ?

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

10) What is the difference between verify and assert commands?


Assert:  Assert allows to check whether an element is on the page or not. The test will stop on the step
failed, if the asserted element is not available. In other words, the test will terminated at the point where
check fails.
Verify: Verify command will check whether the element is on the page, if it is not then the test will carry on
executing.  In verification, all the commands are going to run guaranteed even if any of test fails.
11) What is JUnit Annotations and what are different types of annotations which are useful ?

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-

clickAt (locator, cordString)

13)  What are the advantages of Selenium?


·          It supports C#, PHP, Java, Perl, Phython
·          It supports different OS like Windows, Linux and Mac OS
·          It has got powerful methods to locate elements (Xpath, DOM , CSS)
·          It has highly developer community supported by Google
14) Why testers should opt for Selenium and not QTP?

Selenium is more popular than QTP as

·          Selenium is an open source whereas QTP is a commercial tool

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?

Four parameters that you have to pass in Selenium are

·          Host
·          Port Number
·          Browser
·          URL
16) What is the difference between setSpeed() and sleep() methods?

Both will delay the speed of execution.

Thread.sleep () :  It will stop the current (java) thread for the specified period of time.  Its done only once

·          It takes a single argument in integer format

Ex: thread.sleep(2000)- It will wait for 2 seconds

·          It waits only once at the command given at sleep

SetSpeed () :  For specific amount of time it will stop the execution for every selenium command.

·          It takes a single argument in integer format

Ex: selenium.setSpeed(“2000”)- It will wait for 2 seconds

·          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.

19) How you can use “submit” a form using Selenium ?

You can use “submit” method on element to submit form-

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

·          Support for annotations


·          Support for data-driven testing
·          Flexible test configuration

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.

Explicit Wait :  It is a one-timer, used for a particular search.

22) Which attribute you should consider throughout the script in frame for “if no frame Id as well as
no frame name”?

You can use…..driver.findElements(By.xpath(“//iframe”))….

This will return list of frames.

You will ned to  switch to each and every frame and search for locator which we want.

Then break the loop

23) Explain what is the difference between find elements () and find element () ?

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.

24) Explain what are the JUnits annotation linked with Selenium?

The JUnits annotation linked with Selenium are

·          @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?

Pass the username and password with url

·          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”))

//get test from element and stored in text variable

String text = el.getText();

//assert text from expected

Assert.assertEquals(“Element Text”, text);

28) Explain what is the difference between Borland Silk and Selenium?

seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-1.html 4/5
05/01/2023 20:10 Selenium Test Automation: Selenium Ques $ Ans -1

                         Silk Test Tool                         Selenium Test Tool

·          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

·          Selenium suite has the flexibility to use many languages


·          Silk test uses test scripting language ·           like Java, Ruby,Perl and so on

·          Silk test can be used for client server


applications ·          Selenium can be used for only web application

29) What is Object Repository ?

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.

30) Explain how Selenium Grid works?

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.

31) Can we use Selenium grid for performance testing?

Yes. But not as effectively as a dedicated performance testing tool like Loadrunner.

Posted by Ramesh Kudikala at 13:11

No comments:

Post a Comment
To leave a comment, click the button below to sign in with Blogger.

SIGN IN WITH BLOGGER

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

Simple theme. Theme images by imagedepotpro. Powered by 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

Selenium Test Automation


Saturday, 18 April 2015 About Me

Ramesh Kudikala
selenium que $ans -2
View my complete profile

Webdriver (Selenium ) Interview Questions and answers


Blog Archive
Question 1: What is Selenium 2.0
Answer: Webdriver is open source automation tool for web application. WebDriver is designed to provide a ▼ 
▼  2015 (15)
simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC ▼ 
▼  April (15)
API. Selenium Quiz - 3
Selenium Quiz - 2
Question 2: What is cost of webdriver, is this commercial or open source. Selenium Quiz - 1
Answer: selenium  is open source and free of cost. Java Questions and anwsers
Core Java - Collections -1
Question 3: how you specify browser configurations with Selenium 2.0? Manual Testing Stuff
Answer:  Following driver classes are used for browser configuration
Selenium ques $ans -4
·                     AndroidDriver,
Selenium que $ans -3
·                     ChromeDriver,
selenium que $ans -2
·                     EventFiringWebDriver, Selenium Ques $ Ans -1
·                     FirefoxDriver, 50- Selenium Webdriver interview Ques
ans...
·                     HtmlUnitDriver,
50 - Selenium Webdriver interview Ques
·                     InternetExplorerDriver,
20 Java Collections Interview Questions
·                     IPhoneDriver,
What are the challenges of Selenium Au
·                     IPhoneSimulatorDriver,
Selenium Webdriver interview Question
·                     RemoteWebDriver
Question 4: How is Selenium 2.0 configuration different than Selenium 1.0?
Answer: In case of Selenium 1.0 you need Selenium jar file pertaining to one library for example in case of
java you need java client driver and also Selenium server jar file. While with Selenium 2.0 you need
language binding (i.e. java, C# etc) and Selenium server jar if you are using Remote Control or Remote
WebDriver.

Question5: Can you show me one code example of setting Selenium 2.0?


Answer: below is example
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
driver.findElement(By.cssSelector("#gb_2 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_8 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();

Question 6: Which web driver implementation is fastest?


Answer: HTMLUnitDriver. Simple reason is HTMLUnitDriver does not execute tests on browser but plain
http request – response which is far quick than launching a browser and executing tests. But then you may
like to execute tests on a real browser than something running behind the scenes

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 8:  How do I submit a form using Selenium?


Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));
el.submit();

Question 9: How to capture screen shot in Webdriver?


Answer:
File file= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("c:\\name.png"));

Question 10: How do I clear content of a text box in Selenium 2.0?


Answer:  
WebElement el  =  driver.findElement(By.id("ElementID"));
el.clear();

Question 11:  How to execute java scripts function.


Answer:
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("pass your java scripts");

Question 12:  How to select a drop down value using Selenium2.0?


Answer: See point 16 in below post: 
Click here for answer

Question 13: How to automate radio button in Selenium 2.0?


Answer:
WebElement el = driver.findElement(By.id("Radio button id"));

//to perform check operation


el.click()

//verfiy to radio button is check it return true if selected else false


el.isSelected()

Question 14: How to capture element image using Selenium 2.0?


Answer: click link for answer: 

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 16:  How to capture page title using Selenium 2.0?


Answer:
String title =  driver.getTitle()

Question 17:  How to store page source using Selenium 2.0?


Answer:
String pagesource = driver.getPageSource()

Question 18: How to store current url using selenium 2.0?


Answer: 
String currentURL  = driver.getCurrentUrl()

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();

//assert text from expected


Assert.assertEquals("Element Text", text);

Question 20: How to get element attribute using Selenium 2.0?


Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));

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") ;

Question 21: How to double click on element using selenium 2.0?


Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));

Actions builder = new Actions(driver);


builder.doubleClick(el).build().perform();

Question 22: How to perform drag and drop in selenium 2.0?


Answer:
WebElement source  =  driver.findElement(By.id("Source ElementID"));
WebElement destination  =  driver.findElement(By.id("Taget ElementID"));

Actions builder = new Actions(driver);


builder.dragAndDrop(source, destination ).perform();

Question 23: How to maximize window using selenium 2.0?


Answer:
driver.manage().window().maximize();

Question 24: How to verify pdf content using selenium 2.0?


Answer: Go through below post: 
Road to verify 200 response code of web application in java webdriver
This post will help to verify HTTP response code 200 of web application using java webdriver. As webdriver
does not support direct any function to verify page response code. But using "WebClient" of HtmlUnit API
we can achieve this.

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

 String url = "http://www.google.com/";


 WebClient webClient = new WebClient();
 HtmlPage htmlPage = webClient.getPage(url);

 //verify response
 Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
 Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());

If HTTP authentication is required in web application use below code.

 String url = "Application Url";


           
 WebClient webClient = new WebClient();
 DefaultCredentialsProvider credential = new DefaultCredentialsProvider();
           
 //Set some example credentials
 credential.addCredentials("UserName", "Passeord");          
 webClient.setCredentialsProvider(credential);
           
 HtmlPage htmlPage = webClient.getPage(url);

 //verify response
 Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
 Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());

Road to verify images using java webdriver


In this post I have explained that how to verify images in webdriver using java. As webdriver does not
provide direct any function to image verification, but we can verify images by taking two screen shots of
whole web page using “TakesScreenshot” webdriver function, one at script creation time and another at
execution time,

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;

 public class ImageComparison {

      public WebDriver driver;


      private String baseUrl;
     
      @BeforeSuite
      public void setUp() throws Exception {
         driver = new FirefoxDriver();
         baseUrl = "https://www.google.co.in/";
         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);      
      }
        
      @AfterSuite
      public void tearDown() throws Exception {
         driver.quit();    
      }
       
      @Test
      public void testImageComparison()
               throws IOException, InterruptedException
      {
         driver.navigate().to(baseUrl);
         File screenshot = ((TakesScreenshot)driver).
getScreenshotAs(OutputType.FILE);
         Thread.sleep(3000);
         FileUtils.copyFile(screenshot, new File("GoogleOutput.jpg"));

         File fileInput = new File("GoogleInput.jpg");


         File fileOutPut = new File("GoogleOutput.jpg");

         BufferedImage bufileInput = ImageIO.read(fileInput);


         DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
         int sizefileInput = dafileInput.getSize();                     
         BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
         DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
         int sizefileOutPut = dafileOutPut.getSize();
         Boolean matchFlag = true;
         if(sizefileInput == sizefileOutPut) {                         
            for(int j=0; j<sizefileInput; j++) {
                  if(dafileInput.getElem(j) != dafileOutPut.getElem(j)) {
                        matchFlag = false;
                        break;

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

User above formatted URL in webdriver get method:

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

Road to automate Html5 video with Webdriver (Selenium)


In this post I will show you how to automate HTML5 video.  To automate this we will use java scripts
function to control video. So here we use “document.getElementById("Video ID")” , it return the HTML 5
video object. Using this object we can simulate video. Following are some java script function to handle
video.
1. Play video
            document.getElementById("Video ID").play();  

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

Example: here is example of Webdriver to automate html 5 video, I am using JavascriptExecutor class to


execute java script code.
?
1 public class HtmlVideo {
2   
3 public WebDriver driver;
4   
5 @Test

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 }

Screen Recording (Video) of Java Webdriver script


Sauce lab provided screen capturing functionality to test scripts execution, I was looking same type
functionality to work on local machine and came up across “Monte Media Library” java based library
developed by Werner Randelshofer.. In this post I have described a way to capture screen cast/ Video
recording of selenium/webdriver test script execution.

Step to implement Monte Media library to selenium/Webdriver test scripts.


1.            Download “MonteScreenRecorder.jar” from link http://www.randelshofer.ch/monte/
2.            Add this jar file to your selenium/webdriver eclipse project.
3.            This jar file contain “ScreenRecorder” class, we need to create this class object by following
way.

?
1 GraphicsConfiguration gc = GraphicsEnvironment
2       .getLocalGraphicsEnvironment()
3       .getDefaultScreenDevice()
4       .getDefaultConfiguration();
5
6
7 ScreenRecorder  screenRecorder = new ScreenRecorder(gc,

8       new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),


9       new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,

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 {

16     private ScreenRecorder screenRecorder;

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.

Road to verify PDF file text using java webdriver


In this post I will explain the procedure to verify PDF file content using java webdriver. As  some time we
need to verify content of web application pdf file, opened in browser.
Use below code in your test scripts to get pdf file content.

 //get current urlpdf file url


 URL url = new URL(driver.getCurrentUrl());
                 
 //create buffer reader object

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();

 //save pdf text into strong variable


 String pdftxt = new PDFTextStripper().getText(pdfParser.getPDDocument());
                 
 //close PDFParser object
 pdfParser.getPDDocument().close();

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.

Road to publish Webdriver TestNg report in Jenkins


In this post I will show you how to publish TestNg report on Jenkins server.

Installation TestNG plug-in.


1. After launching Jenkins server go to "Manage Jenkins>>Manage Plugins"
2. Enter TestNg in filter field, you will see “TestNg Results Plugin” like below screen.

http://4.bp.blogspot.com/-sV3E2LDXa50/U7heF0V4G-
I/AAAAAAAAAoo/WnhstOAXZWg/s1600/TestNGEclipse.JPG

3. Click on check box and then click on installation button.

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

4. Enter target name.


5. Click on “Add post Build Action” and select “Publish TestNG Results” option.
http://4.bp.blogspot.com/-
pnACyPnc8xs/U7heC60gz6I/AAAAAAAAAoI/yxMEs2f3lkY/s1600/JenkinsTestNG2.jpg

6. Change TestNg report file name if you have not default.


http://1.bp.blogspot.com/-
TVxo12jEKY8/U7heDAvFuLI/AAAAAAAAAoM/Y0rTTwIfTOE/s1600/JenkinsTestNG3.jpg

7. Click “Apply“ and “Save” button.


8. Go to your created Job you should see “TestNg Result” link.

http://2.bp.blogspot.com/-5UNu4ArJSMQ/U7heDqhkfrI/AAAAAAAAAoY/3qksiu62yC4/s1600/JenkinsTe
stNG4.jpg

9. Put your entire code base into created Job's workspace.

Execution and Report:


1. Build your job.
2. Click on “TestNg Result” link you will show report like below:
http://4.bp.blogspot.com/-3muLRkrZ8Jg/U7heEejLYQI/AAAAAAAAAoc/6ljFgDyHuKY/s1600/JenkinsTes
tNG5.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

How to Set up and launching Selenium Grid?


Download selenium latest jar file from Webdriver

Launching Hub:

Open command prompt and got to your selenium server jar file and run command:

java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 4444 -role hub


screen should be displayed like below.

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

Screen should be displayed like below:

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.

Open Url :localhost:4444/console” you will see like below screen.

http://4.bp.blogspot.com/-Vuw8v0oHBC4/US5oTBRueyI/AAAAAAAAABQ/Enj9AgFqI_A/s400/url.JPG

How to run python webdriver test scripts using Grid2


Prerequisite:
1.            Java and python should be installed and setup path in your machine..
2.            Download xmlrunner.py from below url: http://pypi.python.org/pypi/XmlTestRunner/0.16654
3.            Download and install “setuptools 0.6c11” from below link: http://pypi.python.org/pypi/setuptools
4.            Install selenium 2 in your system using command: > easy_install selenium
5.            Selenium server file should be in machine
Set up and launching Selenium Grid:

      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.

from selenium import webdriver


import unittest

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.

python Grid2.py 5555 WINDOWS firefox


python Grid2.py 5556 WINDOWS iexplore

Where Grid2.py is created test script.


After execution two xml files are generated under project for each execution.

How to run java test scripts using Grid2


Prerequisites. 
1.            Java should be install and setup path in system.
2.            Eclipse should be configured TestNG plugin 
3.            Download the selenium-server-standalone-version.jar from the below location.
4.            TestNG jar file.
Steps to  create and execute test scripts:

1. Launch Grid 2 console(Hub ) and Nodes using below commands:

    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;

    public class WebDriverGrid2Test {

          public WebDriver driver;


 
          @Parameters({"browser", "version", "os"})
          @BeforeClass
           public void setup(String browser, String version, String os) throws MalformedURLException,    
InterruptedException {
                DesiredCapabilities capability=null;   
                capability = gridStting(browser, version, os);
                driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
                driver.navigate().to("http://google.com");  
           }
 
       @Test
       public void testGoogleSearch2() throws InterruptedException{
                 Thread.sleep(3000);
                 WebElement search_input = driver.findElement(By.id("gbqfq"));
                 search_input.clear();
                 search_input.sendKeys("Testing");
                 WebElement search_button = driver.findElement(By.id("gbqfb")); 
                 search_button.click();
         }
 
         @Test
         public void testGoogleSearch1(){
                 WebElement search_input = driver.findElement(By.id("gbqfq"));
                 search_input.clear();
                 search_input.sendKeys("Testing");
                 WebElement search_button = driver.findElement(By.id("gbqfb")); 
                  search_button.click();  
          }
 
         @AfterClass
         public void tearDown(){         
                 driver.quit();
         }
 
         public DesiredCapabilities gridStting(String browser, String version, String os){
                 DesiredCapabilities capability=null; 
                 if(browser.equals("firefox")){
                       System.out.println("Test scripts running on firefox");
                       capability= DesiredCapabilities.firefox();
                       capability.setBrowserName("firefox");    
                       capability.setVersion(version);
                }
 
               if(browser.equals("iexplore")){    
                       System.out.println("Test scripts running on iexplore");
                       capability= DesiredCapabilities.internetExplorer();

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;
             }
   }

3. We need to create TestNG file like as below “Suite.xml” file:

 <?xml version="1.0" encoding="UTF-8"?>


 <suite name="Test case run on Two environment" verbose="3"  parallel="tests" thread-count="2">   
      <test name="Run on Internet Explorer">
           <parameter name="browser"  value="iexplore"/>
            <parameter name="version"  value="8"/>
            <parameter name="os"  value="XP"/>
            <classes>
                <class name="com.test.WebDriverGrid2Test"/>
            </classes>
        </test>  
         <test name="Run on Firefox">
               <parameter name="browser"  value="firefox"/>
               <parameter name="version"  value="13"/>
               <parameter name="os"  value=" XP "/>
               <classes>
                   <class name="com.test.WebDriverGrid2Test"/>
               </classes>
          </test>  
 </suite>

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");

            driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities);


            //driver = new FirefoxDriver();
            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();
        }     
    }
}

Launch Grid
       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

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

Posted by Ramesh Kudikala at 13:12

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.

SIGN IN WITH BLOGGER

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

Simple theme. Theme images by imagedepotpro. Powered by 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

Selenium Test Automation


Saturday, 18 April 2015 About Me

Ramesh Kudikala
Selenium que $ans -3
View my complete profile

Selenium WebDriver methods with Examples


Blog Archive
Selenium WebDriver methods with Examples
▼ 
▼  2015 (15)
1.Browser Back and Forward (NAVIGATION) ▼ 
▼  April (15)
Steps to implement Browser back and forward through Selenium Web Driver
Selenium Quiz - 3
1. Create Driver for any Browser(Mozilla)
Selenium Quiz - 2
2. Go to the URL
3. Navigate to some page in website. Selenium Quiz - 1
4. Use Selenium code to Navigate Back to Main Page. Java Questions and anwsers
CODE: driver.navigate().back(); Core Java - Collections -1
           driver.navigate().forward();
Manual Testing Stuff
Example
Selenium ques $ans -4
WebDriver driver =new FirefoxDriver(); Selenium que $ans -3
driver.get("http://seleniumhq.org/");
selenium que $ans -2
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000);            //delay Selenium Ques $ Ans -1
driver.navigate().back(); 50- Selenium Webdriver interview Ques
driver.navigate().forward(); ans...
------------------------------------------------------------------------------------------------------------------------------ 50 - Selenium Webdriver interview Ques
2.Handling DRAG and DROP
20 Java Collections Interview Questions

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

WebDriver driver = new FirefoxDriver();


driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
 
Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));
 
act.clickAndHold(src).build().perform();                //For each action we need to build and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();---------------------------------------------------------------------------------------------------------------
---------------
3.Making Single Select in Drop down (Option List)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Create an Select object for the Drop Down Element object.
5. Create a List and collect all Options through Select Object.
6. Create a Iterator object for the List.
7. Get the size of the List.
8. Loop through and check for required element.

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

WebElement element = driver.findElement(By.name("selectedCustomer"));


Select dd= new Select(element);
List allOptions= dd.getOptions(); 

//To go through the list, we can use an Iterator. 


//Iterator should be of the same type as the List
//which is WebElement in this case. 

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.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
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
6. Select by VALUE
7. Select by VISIBLE TEXT

Example

WebElement customerdd = driver.findElement(By.name("customerProject.shownCustomer"));


  //convert the element to select object
  Select cust = new Select(customerdd);
  cust.selectByIndex(1);                                       //Select by Index
  Thread.sleep(3000);
  cust.selectByValue("2");                                   //Select by Value
  Thread.sleep(3000);
  cust.selectByVisibleText("mango");                //Select by Visible Text
------------------------------------------------------------------------------------------------------------------------------

5.Multiple Select List Box Window


Steps to make Multiple Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
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

WebElement userdd = driver.findElement(By.name("users"));


Select usr = new Select(userdd);
usr.selectByIndex(0);                     //Select by Index(From Start location)
usr.selectByIndex(2);                     //Select by index(To End Location)
------------------------------------------------------------------------------------------------------------------------------

6.Multiple Select List Box Window - DESELECT


Steps to make Deselect in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL

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

WebElement userdd = driver.findElement(By.name("users"));


Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);

//You can deselect the options


usr.deselectAll();                                          //Deselect ALL selected elements
//or 
usr.deselectByIndex(0);                              //Deselect By using Index
//or
usr.deselectByValue(value);                       //Deselect By using Value
//or
usr.deselectByVisibleText(text);                 //Deselect By using Text
------------------------------------------------------------------------------------------------------------------------------

7.iFRAMES - How to handle Frames in Web Driver


Steps to get Source of each iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame

Example

/*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List frms= driver.findElements(By.tagName("iframe"));  //Frame List


System.out.println(frms.size());
for(int i=0;i
{
 System.out.println(frms.get(i).getAttribute("src"));
}------------------------------------------------------------------------------------------------------------------------------

8.iFRAMES - How to perform action in Frames


Steps to perform Action in iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch iFrame element and create an Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.

Example

WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));


driver.switchTo().frame(ifr);                                     //Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8");  //Perform Action in iFrame
------------------------------------------------------------------------------------------------------------------------------

9.iFRAMES - How to switch to a perticular Frame through index


Steps to switch to perticular iFrame by index through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.

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();
------------------------------------------------------------------------------------------------------------------------------

10. TABS / New Window

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

Steps to iterate through the Window Handles

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to First Window
Handle, Second increment Points to second iterator.

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. 

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();

String parentBrowser= it.next();


String childBrowser = it.next();
driver.switchTo().window(childBrowser);
------------------------------------------------------------------------------------------------------------------------------

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. 

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.
8. When Child browser get closed, Switch from Child browser 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();

String parentBrowser= it.next();


String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);

driver.close();                              //close the current  window(Child Browser)


driver.switchTo().window(parentBrowser);          //Switch to Parent Browser

------------------------------------------------------------------------------------------------------------------------------

11. CALENDAR popups
Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click.

/*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();
------------------------------------------------------------------------------------------------------------------------------

Calendar PopUp - 2 (Customized wait)

 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();
   }
 }

------------------------------------------------------------------------------------------------------------------------------

12. Drop Down MENU

  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.

Please follow the steps mentioned below.

seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 5/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. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action object for Driver
5. Through Action object, move to Parent element.
6. Give a Delay for menu items to be displayed.
7. Fetch the Child item through xpath and Click on it.

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));


Actions act = new Actions(driver); // Create an Action object
//move to the parent menu item
act.moveToElement(parentMenu).build().perform(); 
Thread.sleep(3000);   //wait till the child items are displayed
driver.findElement(By.linkText("Bharat Tirth")).click();

------------------------------------------------------------------------------------------------------------------------------

13. Context Click (Right Click)


We can use keyboard keys to Make a Right Click.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action Object for Driver.
5. Through Action Object, make a Context Click on Menu Parent object.
6. Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.

Example

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));


 
Actions act = new Actions(driver); //Create Action object for Driver

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();

------------------------------------------------------------------------------------------------------------------------------
 

14. JAVA SCRIPT example


We can use java script command to perform actions.
We can write code to fill up the text box through java script.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Create Java Script executor object for the Driver.
4. Store the Java Script command in a String Variable.
5. Java Script Executor object executes the command in the Variable.

JavascriptExecutor js = (JavascriptExecutor) driver;


String jsCmd = "document.getElementsByName('city')[0].value='ban'";
js.executeScript(jsCmd);
------------------------------------------------------------------------------------------------------------------------------

15. Multiple Elements


We can count the number of links present in the page. We can also print the link text of each Web link.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).

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();

------------------------------------------------------------------------------------------------------------------------------

16. Other Browser (Internet Explorer)

Using Internet Explorer with Web Driver.

Please follow the steps mentioned below.


1. Set System Property for the Driver and give path of the IE Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");

WebDriver driver =new InternetExplorerDriver();


driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------

17. Other Browser (Chrome)

Using Chrome with Web Driver.

Please follow the steps mentioned below.

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");

WebDriver driver = new ChromeDriver();


driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------

18. PROXY settings.


Please follow the steps mentioned below.

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

FirefoxProfile profile = new FirefoxProfile();


String PROXY = "xx.xx.xx.xx:xx";
Proxy proxy = new 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);

------------------------------------------------------------------------------------------------------------------------------

19. Page Onload authentication


Sometimes when you are Automating Web pages, you may come across Page onload Authentication
window. This window is not java popup/div. It is windows popup. Selenium directly cannot handle this
windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using Autoit.

Please follow the steps mentioned below.

1.Download Autoit from the following URl


  ( http://www.autoitscript.com/site/autoit/downloads/ )
2.Install downloaded software.
3. Open Script Editor
   Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.
4.Open Object Identifier.
  Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to     identify.
6.Collect the Title Name of window from (AutoIt Window Info.)
7.Write the Script in the Editor.
----------------------------------------------------AUTOIT CODE-----------------------------------------------------

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:

Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM WEBDRIVER\\AUTOIT\\Authentication1.exe");


WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");

------------------------------------------------------------------------------------------------------------------------------

20. File Download


Please follow the steps mentioned below.

1. Create a PROFILE object of Browser.


2. Set Preference, by giving Download destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2 => Indicates a
custom Folder Location
4. Set Preference, A comma-separated list of MIME types to save to disk without asking what to use to open
the file. Default value is an empty string.

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.

FirefoxProfile Prof = new FirefoxProfile();


Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");
 
WebDriver driver = new FirefoxDriver(Prof);
driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-drivers']/table/tbody/tr[1]/td[4]/a")).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

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
String FilePath = "C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------

22. Handling JAVA ALERT


Sometimes you may get alerts as anticipated(through Insert/update/delete operation in database). These
may be JAVA alerts.
Please follow the steps mentioned below to handle  Alerts.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. You get an alert asking to click on 'YES' or 'NO' button.
4. First Confirm if it is JAVA alert window.
5. Write a code to switch the control to Alert window.
6. In the Alert window, either ACCEPT by clicking on 'YES'
    or CANCEL by clicking on 'NO'.

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Alert alert = driver.switchTo().alert();


alert.accept();
//or
alert.dismiss();

Sikuli Automation Tool Integration with Selenium Web driver


How to integrate SIKULI script with SELENIUM WEBDRIVER
Sikuli is a robust and powerful tool to automate and tests user interfaces screenshots. The core of Sikuli
Script is written in Java, which means you can use Sikuli Script as a standard JAVA library in your program.
This article lets you know how to do that.

1. Download and install Sikuli using the self-extracting installer(http://www.sikuli.org/download.html).


Note: Only 32-bit version is provided for using as a standard JAVA library. But SIKULI IDE could run on
both 32-bit and 64-bit Windows systems.

2. Create new Java project (use Eclipse as an example):

3. Fill project name and click Finish:

  
4. Create new class:

5. Fill class name and click Finish:

6. Include sikuli-script.jar, selenium-server-standalone-2.25.0.jar, selenium-java-2.25.0.jar in the


CLASSPATH of your Java project. 

Get sikuli-script.jar from your Sikuli IDE installation path.

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.

Windows, Linux: Sikuli-IDE/sikuli-script.jar


Mac OS X: Sikuli-IDE.app/Contents/Resources/Java/sikuli-script.jar

After adding sikuli-script.jar, selenium-server-standalone-2.25.0.jar, selenium-java-2.25.0.jar as a libraries


into your project, the project hierarchy should look like this:

seleniumhqa.blogspot.com/2015/04/selenium-que-ans-3.html 9/11
05/01/2023 20:11 Selenium Test Automation: Selenium que $ans -3

After click OK:

7. After configuring in build path, create and initialize an instance of Screen object.

SIKULI + SELENIUM WEBDRIVER

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;

public class sikuliFirstTest {

@Test
public void functionName() throws FindFailed {
  
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();

// And now use this to visit Google


driver.get("http://www.google.com");

//Create and initialize an instance of Screen object    


Screen screen = new Screen();

//Add image path  


Pattern image = new Pattern("C:\\searchButton.png");
    
//Wait 10ms for image  
screen.wait(image, 10);
    
//Click on the image
screen.click(image);
  }
}

Here example using SIKULI without Selenium WebDriver:

import org.junit.Test;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

public class sikuliFirstTest {

@Test
public void functionName() throws FindFailed {

//Open FireFox application with google home page   


App firefox = App.open("c:\\Program Files\\MozillaFirefox\\firefox.exe");

//Create and initialize an instance of Screen object    


Screen screen = new Screen();

//Add image path  


Pattern image = new Pattern("C:\\searchButton.png");
    
//Wait 10ms for image  
screen.wait(image, 10);
    
//Click on the image
screen.click(image);

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();
  }
}

Posted by Ramesh Kudikala at 13:13

No comments:
Post a Comment
To leave a comment, click the button below to sign in with Blogger.

SIGN IN WITH BLOGGER

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

Simple theme. Theme images by imagedepotpro. Powered by 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

Selenium Test Automation


Saturday, 18 April 2015 About Me

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

1. What do you know about Selenium? Selenium Quiz - 2


2. What are the technical challenges with selenium?As you know Selenium is a free ware open source testing tool. There are many Selenium Quiz - 1
challenges with Selenium. Java Questions and anwsers
-->Selenium Supports only web based applications
Core Java - Collections -1
-->It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
Manual Testing Stuff
-->When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of
the test cases Selenium ques $ans -4
-->Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications Selenium que $ans -3
-->There is no object repository concept in Selenium, so maintainability of the objects is very high selenium que $ans -2
-->There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
Selenium Ques $ Ans -1
-->Bitmap comparison is not supported by Selenium
50- Selenium Webdriver interview Ques
-->Any reporting related capabilities, you need to depend on third party tools
ans...
-->You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side
50 - Selenium Webdriver interview Ques
of selenium
3. What are the test types supported by Selenium?Selenium could be used for testing the web based applications. 20 Java Collections Interview Questions
The test types can be supported are:1. Functional, What are the challenges of Selenium Au
2. Regression, Selenium Webdriver interview Question
3. Load testing
The automation tool could be implemented for post release validation with continuous integration tools like:
1. Jenkins,
2. Hudson,
3. Quick Build
4. CruiseCont
4. What are the capabilities of Selenium IDE?Selenium IDE (Integrated Development Environment) works similar to commercial
tools like QTP, Silk Test and Test Partner etc. The below mentioned points describes well about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. debugging of the test cases with step-by-step can be done
6. Breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can support an extensibility capability allowing the use of add-ons or user extensions that expand the functionality
of Selenium IDE
5. What are the challenges with Selenium IDE?Selenium-IDE does not directly support:
1. Condition statements
2. Iteration or looping
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
10. Results Report generations
6. Which are the browsers supported by Selenium IDE?Selenium IDE supports only one browser Mozilla Firefox. The versions
supported as of now are:
Mozilla Firefox 2.x
Mozilla Firefox 3.x
The versions not supported as of now are:
7. How to execute a single line command from Selenium IDE?Single line command from Selenium IDE can be executed in two ways
1. Right click on the command in Selenium IDE and select "Execute This Command"
2. Select the command in Selenium IDE and press "X" key on the keyboard
8. How to insert a start point in Selenium IDE?Start point Selenium IDE can be set in two ways

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

Selenium RC - Interview Questions

Selenium RC Interview Questions


1. What are the pre-requisites to run Selenium RC tests with Junit?The pre-requisites to run Selenium RC tests with Junit:
1) Jre 1.5 or better version needs to be installed
2) /jre/bin folder must be added in environment variable "path"
3) Junit folder path must be added to path or build path in eclipse
4) Selenium Java Client drivers needs to be added to the path for execution
2. How to configure Selenium RC with eclipse to run Junit Tests?1) Download eclipse. click here to download the software
2) Open eclipse -> Workspace Launcher window will open
3) Create a workspace by giving meaningful name
3) Click on Workbench
4) Create a project of type java
5) Create a package under src folder of the package
6) Add Junit to the build path
7) Add selenium rc java client driver to the build path
8) Now drag and drop your test script (.which is exported from Selenium IDE) to the package created
3. Which is the command used for running the Selenium RC Server?The procedure followed to run the Selenium RC Server is:
1. Open the command prompt.
2. Change the folder path to Selenium RC Server
3. Issue the command "java -jar selenium-server.jar"
4. For more options on how to start selenium server. Please have a look at
4. How do you run selenium commands in slow motion in Selenium RC?You can run the selenium commands in RC slow motion by
two ways:
selenium.setSpeed
thread.sleep
5. What is the difference between Thread.Sleep() and Selenium.setSpeed()?
selenium.setSpeed
thread.sleep
6. Why do you use assert and verify statements in Selenium RC without referring to selenium?SeleneseTestCase is the class which is
having
1. assertTrue
2. verifyTrue
3. assertEquals
4. verifyEquals
We use SeleneseTestCase class to extend the selenium test class file.
For Ex: the test class is declared as follows
public class BookFlightSel1 extends SeleneseTestCase
In the above example SeleneseTestCase is the base class and BookFlightSel1 is the derived class. So, we can directly call and use the
parent class methods verify and assert without instantiating the class in BookFlightSel1 class.
7. Which are the annotations generated with JUnit 4 tests in Selenium IDE?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
8. What are the challenges with Selenium RC test suites when running in JUnit?The challenges with Selenium RC test suites when
running in JUnit
1. Each test case of Selenium RC test will invoke the browser and closes after playing back
2. All the Test cases cannot run on a single browser session

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.

Answer: Selenium 2.0 is a consolidation of two web testing tools:


a) Selenium RC and
b) Web Driver,
It claims to give best of both words: Selenium and Web Driver.
2: Why are two tools being combined as Selenium 2.0?
Answer: Selenium 2.0 promises to give much cleaner API than Selenium RC and at the same time not being restricted by JavaScript
Security restriction like same origin policy.
3: So everyone is going to use Selenium 2.0?
Answer: Well no, for example if you are using Selenium Perl client driver than there is no similar offering from Selenium 2.0 and you
would have to stick to Selenium 1.0 till there is similar library available for Selenium 2.0
4: So how do I specify my browser configurations with Selenium 2.0?
Answer: Selenium 2.0 offers following browser/mobile configuration:
a) Android Driver,
b) Chrome Driver,
c) EventFiringWebDriver,
d) Firefox Driver,
e) HtmlUnitDriver,
f) InternetExplorerDriver,
g) IPhoneDriver,
h) IPhoneSimulatorDriver,
i) RemoteWebDriver
And all of them have been implemented from interface WebDriver.To be able to use any of these drivers, you need to instantiate their
corresponding classes.
5: How is Selenium 2.0 configuration different from Selenium 1.0?
Answer: In case of Selenium 1.0, you need Selenium jar file pertaining to one library; for example, in case of Java you need Java client
driver and also Selenium server jar file. With Selenium 2.0, you need language
Binding (i.e. Java, C#, etc) and Selenium server jar if you are using Remote Control or Remote Web Driver.
6. Selenium Benefits over Web Driver.
Selenium supports many browsers and many languages, Web Driver needs native implementations for each new language/browser
combo.
Very mature and complete API
Currently (Sept 2010) supports JavaScript alerts and confirms better
Benefits of Web Driver Compared to Selenium
• Native automation faster and a little less prone to error and browser configuration
• Does not Requires Selenium-RC Server to be running
• Access to headlessHTMLUnit can allow really fast tests
• Great API
7. What is Web Driver?
Web Driver 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.

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.

Selenium FAQS asked in Interviews


1. What is data driven framework?
This frame work is used when an application is test with multiple sets of data. The data is passed to the scripts from data files like
excel files, csv files, ODBC (Open Database Connectivity) and ADO (ActiveX Data Objects) objects.
Data driven framework is a systematic approach to test an application. It may contain all the structured information like data driven
files, library functions, and user defined functions. Using the driver script, we can import theses files as a input to the application
and test it. This is called data driven frame work. Data driven approach is being by most of the industries
2 what is keyword, hybrid framework?
Frame Work is the model or structure we follow for a Project. It is the approach that we follow to automate the Project. There are so
many types of framework in QTP.
1. Data driven frame work
2. Keyword driven frame work
3. Module driven framework
4. Hybrid driven frame work
The framework you choose depends on the model of your Project. Usually most of projects fall under hybrid driven frame work.
Data driven framework:
Keyword driven framework:
Module driven frame work:
Hybrid Frame work:
This will be the combination of the any frameworks like Keyword driven+DataDriven or Data driven + modular driven. we will
divide entire project in to modules and write functions or procedures for each and every module and automate the project. Hybrid
driven framework: it is combination of Data driven and module driven framework.Firstly we should add the objects to repository (
Shared repository is preferable) Then we can generate/write scripts for each functionality and save them as the library files ( .vbs
files)Then we have to associate all these library files(which are generated to test different functionalities) to Quick Test. Here we
divide the entire project in to modules and start automation by writing data driven scripting for each one of them. We will have test
data either in excel sheet or flat files or from database...we will pass that test data in to the script and perform data driven testing.
3 what is iframe?
An <iframe></iframe> element allows the placement of an inline frame within an HTML document, which allows the display of
another, separate document. Any content between the start and close tag of the <iframe> element is ignored.
There are various ways of selecting an IFrame with selenium and accessing data within the IFrame: By
Name:selenium.selectFrame("mainFrame"); //name of the IFrame
By DOM:
Remember index starts at 0, so "index=1″ will select the second IFrame. We can call the selectFrame() function multiple times to
select the nested IFrames:
selenium.selectFrame("index=1″);
selenium.selectFrame("index=1″); will select the second IFrame within the second IFrame from the root
4 what is difference b/w xpather and xpath checker?
Firebug - the right-click "copy XPath" command copies the path as all lower-case, and some XML parsers (like the MXSML parser
used in Final Builder) are case-sensitive - so you'll need to correct the casing of your Firebug-copied XPath statement otherwise your
parser won't find any matching nodes.
XPather
...generates
The XPather is a simple
selenium.selectFrame("dom=window.frames[1]"); //second IFrame By Index: selenium.selectFrame("index=1″); //second
IFrameXPaths while browsing or inspecting HTML/XML/*ML documents; evaluates your XPaths and inspects the results; extracts the

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

Data Driven Testing using Selenium RC with JUnit


How to do Data Driven Testing using Selenium RC with JUnit
There are many ways to do Data driven tests.I used Excel sheet for reading data and FileInputStream method.
Below script explains you how to Read data from excel sheet and use the data to search google.
I am using Eclipse, selenium RC, Junit and Excel sheet for this script.

--->Create a Java project in eclipse.


--->Create a new class DatadrivenJUnit.
--->Paste the below code in Eclipse.
--->Chnage the path of excel file according to your requirement.
Please note that selenium will support only .xls format plese do not forget to change the excel file to .xls if you are using MS-
office2007.
Below is the code
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;

public class DatadrivenJUnit extends SeleneseTestCase


{
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception 
{
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testDatadrivenJUnit() throws Exception
{
FileInputStream fi=new FileInputStream("F:\\Framework\\testdata\\search.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);

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();
}
 }

Data Driven Testing Using Selenium RC with TestNG


How to do Data Driven Testing using TestNG 
There are many ways to do Data driven tests.I used Excel sheet for reading data and FileInputStream method.
Below script explains you how to Read data from excel sheet and use the data to search google.
I am using Eclipse, selenium RC, TestNG and Excel sheet for this script.

--->Create a Java project in eclipse


--->Create a package name as test
--->Create a new class DatadriventestNG.
--->Paste the below code in Eclipse.
--->Chnage the path of excel file according to your requirement.
Please note that selenium will support only .xls format plese do not forget to change the excel file to .xls if you are using MS-
office2007.
Below is the code

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 {

  FileInputStream fi=new FileInputStream("F:\\Framework\\testdata\\search.xls");


Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
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();
   
 }
 }

Login Scenario - Providing Login Detail from Excel Sheet


Excel Sheet format should be in .XLS format

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.*;

public class Loginexcel {


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, "*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();
}

Write results to excel sheet


Write results to excel sheet 

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.*;

public class Importexport1 {


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, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}

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

Database Connection Using Selenium


Database Connection Using Selenium 

MS Access with Java through JDBC-ODBC connection


Microsoft has provided a method to build a quick Jet-Engine database on your computer without the need for any specific database
software (it comes standard with Windows). Using this method, we can even create a blank Microsoft Access database without
having MS Access installed!
MS Access data bases can be connected to via ODBC. Instead of accessing the database directly, we can access it via a Data Source
Name (DSN). Here's how to set up a DSN on your system:
Open Windows' ODBC Data Source Administrator as follows: 
In Windows 95, 98, or NT, choose Start > Settings > Control Panel, then double-click the ODBC Data Sources icon. Depending on your
system, the icon could also be called ODBC or 32bit ODBC. 
In Windows 2000, choose Start > Settings > Control Panel > Administrative Tools > Data Sources. 
In the ODBC Data Source Administrator dialog box, click the System DSN tab. 
Click Add to add a new DSN to the list. 
Scroll down and select the Microsoft Access (.MDB) driver 

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();
}
}

Creating test suite using Junit and eclipse in selenium


How to create test suite using Junit and eclipse in selenium 

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(); 
}

Identify dynamic element in selenium


How to identify dynamic element in selenium 

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')].

using functions in xpath in selenium


How to use functions in xpath in selenium 

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')].

WebDriver with TestNG - Gmail Login Functionality


Below is the code for GMAIL Login functionality using WebDriver with TestNG

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();
 }
}

Selenium Grid - Setup in System


Selenium Grid Setup

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. 

Setting up Parallel execution on a single machine

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

“ant -Dport =5556 launch-remote-control”

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.

Setting up parallel execution for different machines and different environments

In this case start the Hub normally as you do in any of the system. 

For starting the remote control use the following command.

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. 

Advantages of Selenium Grid

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.

Technical challenges with selenium


As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.

1.Selenium Supports only web based applications


2.It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
3.When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the
test cases
4.Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
5.There is no object repository concept in Selenium, so maintainability of the objects is very high
6.There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
7.Bitmap comparison is not supported by Selenium
8.Any reporting related capabilities, you need to depend on third party tools
9.You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side
of selenium

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 –

 the scripts should run as intended without any issues.ü


 the code and the flows should be easy to understand.ü
 the scripts should be easy to maintain in case of any changes.ü

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.

Advantages of Modular Framework


 Test Scripts can be created in relatively less time as the reusable functions need to be created only once.ü
 Effort required to create test cases is also lesser due to code reuse.ü
 If there are any changes in the reusable functions, the changes need to be done in only a single place. Hence script maintenance is
easier.ü
Disadvantages of Modular Framework
 Since data is still hardcoded in the script, the same test case cannot be run for multiple data values without changing data after each
run.ü
 Additional time is spent in analyzing the test cases to identify with reusable flows.ü
 Good programming knowledge is required to create and maintain function libraries.ü

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.

Advantages of Hybrid Framework


 The main advantage of this approach is that you can use the best features from all the types of frameworks to create your own.ü
Disadvantages of Hybrid Framework
 The framework is highly complex and needs very good programming expertise and experience to build a Hybrid Framework from
scratch.ü

Android Mobile Automation Testing with Selenium WebDriver


WebDriver with Android Device

Introducing Android WebDriver 


Selenium WebDriver is a browser automation tool which provides a lightweight and elegant way for testing web apps. Selenium
WebDriver is now available as an SDK extra in the Android SDK, and supports 2.3 (Gingerbread) and onwards!
Whether or not your site is optimized for mobile browsers, you can be sure that users will be accessing it from their phones and
tablets. WebDriver makes it easy to write automated tests that ensure your site works correctly when viewed from the Android
browser. We’ll walk you through some basics about WebDriver and look at it in action.
WebDriver(Android Driver) Baciscs
WebDriver tests are end-to-end tests that exercise the web application just like a real user would. WebDriver models user
interactions with a web page such as finger flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5
features such as local storage, session storage and the application cache. Those tests run as part of an Android tests project and are
based on Junit. They can be launched from Eclipse or the command line. WebDriver tests can be wired with a continuous integration
system and can run on phone and tablet emulators or real devices. Once the test starts, WebDriver opens a WebView configured like
the Android browser and runs the tests against it. 

Installation of Android SDK


1. Download installer from http://developer.android.com/sdk/index.html 
2. Install it to a location (like: C:\Program Files\Android) 
3. Launch “SDK Manager.exe” 
4. It will launch “Android SDK and AVD Manager”. By default “Installed packages” will be highlighted. On the pop up “Choose
Packages to install”, there will be some packages selected already. Go ahead with the “Install”.
http://4.bp.blogspot.com/-oucdfIzwlnw/UPPrgLW9ETI/AAAAAAAAAE8/gS6e-krw5Nk/s320/AVD+Manager.png

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

Install webdriver APK in Android Device 


1. Download “android-server-2.0.2rc3.apk ” from the following location http://code.google.com/p/selenium/downloads/list
2. Copy the above downloaded file into folder “C:\Program Files\Android\android-sdk\platform-tools”
3. Run the “Command Prompt” as administrator.
4. Execute “cd C:\Program Files\Android\android-sdk\platform-tools”
5. Execute the command “adb install android-server-2.0.2rc3.apk”
6. We also need to set up Port forwarding, run the command “adb forward tcp:8080 tcp:8080"
7. Click on the WebDriver app on Emulator and this will make the android server available at “http://localhost:8080/wd/hub”.
Opening this URL in Firefox will show up a blank page on success.
8. Confirm the following settings on your emulator: Settings -> Applications -> Development -> Check "USB debugging", "Stay Awake"
and "Allow mock locations".
9. Launch the emulator, it will have Webdriver installed. When you launch the Webdriver, it will confirm “jetty started”
10.WebDriver installed successfully as shown in below image.
http://2.bp.blogspot.com/-
pJzisybpOpM/UPPsKiLLx4I/AAAAAAAAAFU/zKgbsJuFf3o/s320/WebDriver+in+Android+virtual+device.png

Open the eclipse and try with below examples.


TC – Gmail Login
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.android.AndroidDriver;
public class Gmail {
public static void main(String args[])throws Exception
{
AndroidDriver ad=new AndroidDriver();
System.out.println("Started");
ad.get("http://www.gmail.com");
System.out.println("Application Title"+ ad.getTitle());
Thread.sleep(2000);

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

Build.xml file code


http://3.bp.blogspot.com/-yv-FjhSa82I/URoRTS9hlyI/AAAAAAAAAGU/gCo_OjwueS0/s320/build.XML+Code.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

Steps to Configure Selenium WebDriver in Android Device


Steps to Configure Selenium Web Driver in Android Device

1. Install  Android SDK 


Download the SDK zip file and unzip in your local computer.

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)

2. Install the ADT Plugin for Eclipse-


Goto Help > Install New Software....>> Add
https://dl-ssl.google.com/android/eclipse/
3.Configure ADT Plugin
Window > Preferences...>>Android
Set the SDK location to where is your Android SDK has been installed.
Location will be something like:  C:\android\android-sdk-windows

4. Add the new AVD


In Eclipse goto Window >>AVD Manager>>
Create new AVD by clicking on “New” button.(Give the AVD  name  and select the Target)

5.Now download the Android APK 


http://code.google.com/p/selenium/downloads/detail?name=android-server-2.21.0.apk&can=2&q=
Copy the file and paste it in the “Platform-tools” folder of the unzipped Android SDK.
Location will be something like “C:\android\android-sdk-windows\platform-tools “

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”

7.  Find the installed emulator device id .


open the command prompt ( cmd ) and run the following command 
adb devices
Emulator device id will be something like “emulator-5554”

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"

9. Install the Android server by running the following command


adb -s emulator-id -e install -r  android-server-2.21.0.apk

10. Start the Android WebDriver application by running the following command


adb -s emulator-id shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug true

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

Selenium Database Connectivity


Prerequisites:

Download - mysql-connector-java-5.1.0-bin.jar and add it to your project


Create a table with some data

Snippet:

import java.sql.*;
import javax.sql.*;

public class dbconnection


{
public static void main(String args[])
{
String email;
String dbUrl = "jdbc:mysql://localhost:3306/test";  //This URL is based on your IP address
String username="username"; //Default username is root
String password="password"; //Default password is root
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select email from users where user_id = 1;";

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

WebDriver Interview Questions and answers

1.  Difference between Absolute path & Relative path.


Absolute path will start with root path (/) and Relative path will from current path (//)
Absolute xPath
: /html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div[@id='main']/div[@id='Blog1']/div[1]
/div[1]/div/div[1]/div/h3/a

Relative xPath : //h3/a[text()='Working on New Window']


2.  Tell me some TestNG Annotations.
@Test,@Parameters,@Listeners,@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest,
@DataProvider,@BeforeGroups,@AfterGroups,@BeforeClass,@AfterClass,
@BeforeMethod,@AfterMethod,@Factory
http://testng.org/doc/documentation-main.html#annotations

3.  What are desiredcapabilities?


Desired Capabilities help to set properties for the Web Driver. A typical use case would be to
set the path for the Firefox Driver if your local installation doesn't correspond to the default
settings.
https://code.google.com/p/selenium/wiki/DesiredCapabilities
4.  Difference between Selenium RC and Selenium Web driver.
 Difference between Selenium RC and Selenium Web driver.

Selenium RC Selenium Web driver


Selenium RC’s architecture is way more complicated. Web Driver’s architecture is simpler than Selenium
RC’s.
Selenium RC is slower since it uses a JavaScript Web Driver is faster than Selenium RC since it speaks
program called Selenium Core.This Selenium Core is directly to the browser uses the browser’s own
the one that directly controls the browser, not you. engine to control it.
Selenium Core, just like other JavaScript codes, can Web Driver interacts with page elements in a more
access disabled elements. realistic way.
Selenium RC’s API is more matured but contains Web Driver’s API is simpler than Selenium RC’s. It
redundancies and often confusing commands. does not contain redundant and confusing
commands.
Selenium RC cannot support the headless HtmlUnit Web Driver can support the headless HtmlUnit
browser. It needs a real, visible browser to operate browser.
on.
Selenium RC Has Built-In Test Result Generator. Web Driver has no built-in command that
Selenium RC automatically generates an HTML file of automatically generates a Test Results File.
test results. 
Selenium RC needs the help of the RC Server in order web Driver directly talks to the browser
to do so.
Selenium RC can support new browsers It cannot readily support new browsers
5.  Difference between Web driver listener and  TestNG Listener.
TestNG and Web driver Listener have different interfaces to implement and call them. They both
modify respective behaviour. You can use Listeners in Annotation. Below 2 URL gives the
 detailed  list of listener and their interfaces.
http://testng.org/doc/documentation-main.html#testng-listeners
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/events/
AbstractWebDriverEventListener.html
6. Describe your framework.

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");

22. Difference between flex and flash application.


In flash there is no code just based on creativity(design) we will complete the
work(time consuming process) whereas flex contain some small functions
which is integrated with mxml,PHP..(no tool is there to develop
 flex we want to use the properties of css and style sheet)
23. What is Error Collector in TestNG? What is its use?
This class allows the collection of errors during the process of retrieving the
test data for the test method parameters
http://testngdatabind.sourceforge.net/apidocs/net/sf/testng/databinding/core/error/
ErrorCollector.html

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

29. Is it possible test web services using selenium?


Using Jmeter we can test how one website is talking to each other means time taken to
send data, feeds, messages from one website to other website. Jmeter does a nice job
of doubling for performance and api tests.
30. How to refresh a page without using context click?
1.Using sendKeys.Keys method
2.Using navigate.refresh() method
3.Using navigate.refresh() method
4.Using get() method
5.Using sendKeys() method
1.Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);

2.Using navigate.refresh() method


driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html");
driver.navigate().refresh();

3.Using navigate.to() method


driver.get("http://ruchi-myseleniumblog.blogspot.in/2014/01/selenium-hybrid-framework-using.html");
driver.navigate().to(driver.getCurrentUrl());

4.Using get() method


driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/basic-core-java-interview-questions.html");
driver.get(driver.getCurrentUrl());

5.Using sendKeys() method


driver.get("https://accounts.google.com/SignUp");

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.

34. How to handle auto complete box in web driver?


By typing in box and capturing list elements
driver.findElement(By.id("your searchBox")).sendKeys("your partial keyword");
Thread.sleep(3000);
List listItems = driver.findElements(By.xpath("your list item locator"));
listItems.get(0).click();
driver.findElement(By.id("your searchButton")).click();
35. How to get the name of browser using Web Driver?
public class JsExecute
{
WebDriver driver;
JavascriptExecutor js;
@Before
public void setUp() throws Exception
{
driver=new FirefoxDriver();
driver.get("http://www.google.com");
}
@Test
public void test()
{
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return navigator.appCodeName"));
}}
OR
String s = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
System.out.println("Browser name : " + s);
36. How to handle colors in web driver?
Use getCssValue(arg0) function to get the colors by sending 'color' string as an argument.
Example
String col = driver.findElement(By.id(locator)).getCssValue("color");

37. How to pass parameters from testng.xml into  test case.


package programs;

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;

public class Parallelexecution {

 private WebDriver driver = null;

 @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.

                                                 

38. How to get text from captcha image??


driver.findElement(By.xpath(".//*[@id='SkipCaptcha']")).click();
String attr = ie.findElement(By.xpath(".//*[@id='SkipCaptcha']")).getAttribute("value");
System.out.println("The value of the attribute 'Name' is " + attr);

39. Is there a way to click hidden LINK in web driver?


String Block1 = driver.findElement(By.id("element ID"));
JavascriptExecutor js1=(JavascriptExecutor)driver;
js1.executeScript("$("+Block1+").css({'display':'block'});");

40. What Class Extends Web Driver?


AndroidDriver, ChromeDriver, EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver,
InternetExplorerDriver, IPhoneDriver, PhantomJSDriver, RemoteWebDriver, SafariDriver

41. What are the APIs that support Web Driver?


API are  nothing but collection of all selenium commands for Locating UI Elements
(WebElements),Fetching a Page,User Input  etc…

42. How to disable cookies in browser.


Using deleteAllVisibleCookies() in selenium

43. "We have heard about frameworks well it can be


 broadly classified into these TDD, BDD and ATDD frameworks .What’s the Difference?"
For Details please see: http://assertselenium.com/2012/11/05/difference-between-tdd-bdd-atdd/

44. How to change user agent in Firefox by selenium  web driver.


FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
Web Driver driver = new FirefoxDriver(profile);

45. What is Selenese?


Selenese is HTML language based command, which is used in Selenium IDE.
46.Differences between QTP and selenium.
1) Selenium generates a proxy while starting browser. QTP does not
2) QTP uses only Vb script. Selenium is available in many languages
3) QTP is paid and selenium is free.
4) You can run script from a particular line in QTP but in selenium, you cannot.
5) Selenium works on all browsers. QTP only works on IE, mozilla. Support from chrome has been introduced lately.
6) QTP is more organized and user friendly
7) Selenium requires more technical skills
8) QTP can also be used on desktop based applications but selenium cannot be used
47. What is the MOST challenging test problem in my career in Automation?
In my career
Changing XPATHS' between testing server and production server-by keeping generic xpath
Keep separate property files for production and UAT
automating flash apps
Mobile Automation

48. “Suppose developer changed the existing image to new image with same xpath. Is test case pass or fail?"
Pass

49. How to handle network latency using selenium? 


Using driver.manage.pageLoadingtime for network latency

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.

51. What are the different types of driver implementation?


AndroidDriver, AndroidWebDriver, ChromeDriver, EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver, InternetExplorerDriver,
IPhoneDriver, IPhoneSimulatorDriver, RemoteWebDriver, SafariDriver, WebDriverBackedSelenium

52. Code for Opening Firefox browser?


Webdriver driver=new FireFoxdriver();

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.

selectByVisibleText - select by the text displayed in drop down


selectByIndex  - select by index of option in drop down
selectByValue  - select by value of option in drop down

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");

55. How to work with dynamic web table?


You can get the total number of tags within a tag by giving the xpath of the
  element by using  this function -
List ele = driver.findElements(By.xpath("Xpath of the table"));
Now you can use a for each loop to loop through each of the tags in the above list
and then read each  value by using getText() method.

56. Detail about TestNG Test Output folder.


It is the directory where reports are generated. Every time tests run in a suite, TestNG
creates index.html and  other files in the output directory.

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

58. What is object repository?


It is collection of object names their properties, attributes and their values .It maye be
 excel, XML,property file or text file

59. TestNG vs. Junit?


Advantages of TestNG over Junit
In Junit we have to declare @BeforeClass and @AfterClass which is a constraint where as in TestNG there is no constraint like this.
-->Additional Levels of setUp/tearDown level are available in TestNG like @Before/AfterSuite,@Before/AfterTest and
@Before/AfterGroup
No Need to extend any class in TestNG.
There is no method name constraint in TestNG as in Junit. You can give any name to the test methods in TestNG
-->In TestNG we can tell the test that one method is dependent on another method where as in Junit this is not possible. In Junit each test
is independent of another test.
Grouping of testcases is available in TestNG where as the same is not available in Junit.
-->Execution can be done based on Groups. For ex. If you have defined many cases and segregated them by defining 2 groups as Sanity and
Regression. Then if you only want to execute the “Sanity” cases then just tell TestNG to execute the “Sanity” and TestNG will
automatically execute the cases belonging to the “Sanity” group.
Also using TestNG your selenium test case execution can be done in parallel.

For more Details Go to : http://www.mkyong.com/unittest/junit-4-vs-testng-comparison/


60. What is the difference between @before method and @beforeclass.
In JUnit4 @Before is used to execute set of preconditions before executing a test.
 For example, if there is a need to open some application and create a user before
executing a test, then this annotation can be used for that method.  Method that is
marked with @Before will be executed before executing every test in the class.
If a JUnit test case class contains lot of tests which all together need a method
which sets up a precondition  and that needs to be executed before executing the

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.

61. What are the different Parameters for @Test annotation? 


Parameters are keywords that modify the annotation’s function.
For more details Go to: http://testng.org/doc/documentation-main.html#parameters

62. Can we run group of test cases 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 regression test or smoke test
 @Test(groups = {"regressiontest", "smoketest"})
 For more details please see: http://testng.org/doc/documentation-main.html#test-groups

63. Differences between Selenium web driver, IDE and RC?


http://qtpselenium.com/selenium-tutorial/difference-between-ide-rc-webdriver/
64. How to highlight an object like qtp/uft does through selenium and java?

How to highlight an object with selenium and java

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;};");

68. How to mouse hover on an element?


Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();

69. How to switch between the windows?


private void handlingMultipleWindows(String windowTitle) {
            Set windows = driver.getWindowHandles();
            for (String window : windows) {
                driver.switchTo().window(window);
                if (driver.getTitle().contains(windowTitle)) {   return;   }     }     }

70. How to switch between frames?


WebDriver's driver.switchTo().frame() method takes one of the three possible arguments:
A number.
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index "0", the second at index
"1" and the third at index "2". Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that
frame.

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.

73. Difference between find element () and findelements ()?


findElement() :
Find the first element within the current page using the given "locating mechanism".
Returns a single WebElement.
findElements() :
Find all elements within the current page using the given "locating mechanism".
Returns List of Web Elements.

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/

76. Write down scenarios which we can't automate?


Barcode Reader, Captcha etc.
77. In TestNG I have some test's   Test1-Test2-Test3-Test4-Test5I want to run my execution  order is Test5-Test1-Test3-Test2-
Test4.How do you set the execution order can you explain for that?
Use priority parameter in @test annotation or TestNG annotations.
78. Differences between jxl and ApachePOI.
jxl does not support  XLSX files
jxl exerts less load on memory as compared to ApachePOI
jxl doesn't support rich text formatting while ApachePOI does.
jxl has not been maintained properly while ApachePOI is more up to date.
Sample code on Apache POI is easily available as compare to jxl.

79.How to ZIP files in Selenium

// Sample Function to make zip of reports


 public static void zip(String filepath){
  try
  {
   File inputFolder=new File('Mention file path her");
   File outputFolder=new File("Reports.zip");
   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFolder)));
   BufferedInputStream in = null;
   byte[] data  = new byte[1000];
   String files[] = inputFolder.list();
   for (int j=0; j    {
    in = new BufferedInputStream(new FileInputStream
    (inputFolder.getPath() + "/" + files[j]), 1000); 
    out.putNextEntry(new ZipEntry(files[j]));
    int totalcount;
    while((totalcount= in.read(data,0,1000)) != -1)
    {
     out.write(data, 0, totalcount);
    }
    out.closeEntry();

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

81. If Default port no is busy how to change port no?


We can use any port number which is valid.. First create an object to remote control configuration.
Use 'setPort' method and provide valid port number(4545,5555,5655, etc).. There after attach this
remote control configuration object to selenium server..i.e
RemoteControlConfiguration r= new RemoteControlConfiguration();
r.setPort(4567);
SeleniumServer s= new SeleniumServer(r);

82. Does Selenium support https protocols?


Yes
83. Majorly asked test scenario with framework in Interviews?
Majorly asked are:
·         Login for Gmail scenario
·         Goggle search and finding no of results
·         Downloading a file and save it
·         Checking mails and deleting them
·         Do shopping in flipkart.com

84. Selenium support mobile applications?


No, it is browser automation tool, it only automates Websites opening in mobile browser, and mobile APPs
 can't be automated.

85. What is wraps Driver?


For casting selenium instance to selenium2 (webdriver). wraps driver is used.
For more details.
http://selenium-junit4-runner.btmatthews.com/apidocs/com/btmatthews/selenium
/junit4/runner/WrappedDriverFactory.html

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

87. Difference between assert and verify in selenium  web driver.


When an “assert” fails, the test will be aborted. Assert is best used when the
 check value has to pass for  the test to be able to continue to run log in.
Where if a “verify” fails, the test will continue executing and logging the failure.
Verify is best used to  check non critical things. Like the presence of a
 headline element.

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']

89. How to do Applet testing using selenium? 


Please see below URLs:
http://docs.codehaus.org/display/FEST/Selenium
https://code.google.com/p/festselenium/

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.

95. List the browsers, OS supported by the Selenium


Windows Linux Mac
IE Y NA NA
FF Y Y Y
Safari Y N Y

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.

100. In what all case we have to go for  “JavaScript executor”.


Consider FB main page after you login. When u scrolls down, the updates get loaded. To
 handle this activity, there is no selenium command. So you can go for javascript to set
the scroll down value like driver.executeScript("window.scrollBy(0,200)", "");

Posted by Ramesh Kudikala at 13:17

8 comments:

ProPlus Logics 16 December 2018 at 21:05

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

Chris Hemsworth 6 June 2019 at 01:50

The above article "Selenium ques $ans -4" is more informative. This is more helpful for our selenium training in chennai. Thanks
for sharing

Reply

infantroshow 12 August 2019 at 05:36

very useful post thank you sharing this post


Selenium training in chennai | Selenium training in velachery

Reply

akhilapriya404 19 August 2019 at 22:14

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

merlin 23 June 2020 at 06:33

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

I am very glad when I read this blog post


Thanks for sharing valuable information.
Keep on posting...

Windows Hosting
Linux Hosting
Shared Web Hosting

Reply

Haappy Herbs By Shrutika 5 April 2022 at 22:16

Hey! This blog is more informative and user friendly


Thank you so much for giving this information to me..

best organic face cream


best shampoo for hair fall control and dandruff 
nourishing hair treatment
Ayurvedic fairness cream

Reply

RgEnterprises 21 June 2022 at 21:09

I'm very Happy when I read this post


Private Finance Companies In Chennai
Best Private Finance Company in Chennai

Reply

To leave a comment, click the button below to sign in with Blogger.

SIGN IN WITH BLOGGER

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

Simple theme. Theme images by imagedepotpro. Powered by Blogger.

seleniumhqa.blogspot.com/2015/04/selenium-ques-ans-4.html 38/38

Vous aimerez peut-être aussi