How to run TestNG tests one-by-one - selenium

I have a test suite and I want to run tests form XML file one-by-one. But when I'm running it, it runs all TCs at the same time (I have 3 open browsers at the same time).
My XML:
<suite name="TestingSuite" preserve-order="true" parallel="false" verbose="10">
<test name="Test1">
<classes>
<class name="guiAndFunctianal.LoginFail" />
<class name="guiAndFunctianal.LoginAsManager" />
<class name="guiAndFunctianal.CreateUserTest" />
</classes>
</test>
</suite>
My TCs looks like this:
public class LoginFail extends AbstractTest{
# BeforeTest
public void openBrowser() {
openBrowserFireFoxAllTcs();
}
# Test
public void main (){
}
# AfterTest
public void quit() {
driver.quit(); }
AbstractTest
public class AbstractTest {
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
public void openBrowserFireFoxAllTcs() {
driver.get("some URL");
}

I assume you want sequential execution. Open a browser>finish testing>close browser and then repeat the same for other browsers. If that's case I would do the following:
TestNG.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" junit="false" parallel="false" configfailurepolicy="skip" thread-count="5" skipfailedinvocationcounts="false" data-provider-thread-count="10" group-by-instances="false" preserve-order="true" allow-return-values="false">
<test name="firefox" junit="false" skipfailedinvocationcounts="false" preserve-order="true" group-by-instances="false" allow-return-values="false">
<parameter name="browser" value="firefox" />
<classes>
<class name="com.github.tests.GitHubHomePageTests" />
</classes>
</test>
<test name="ie" junit="false" skipfailedinvocationcounts="false" preserve-order="true" group-by-instances="false" allow-return-values="false">
<parameter name="browser" value="ie" />
<classes>
<class name="com.github.tests.GitHubHomePageTests" />
</classes>
</test>
<test name="chrome" junit="false" skipfailedinvocationcounts="false" preserve-order="true" group-by-instances="false" allow-return-values="false">
<parameter name="browser" value="chrome" />
<classes>
<class name="com.github.tests.GitHubHomePageTests" />
</classes>
</test>
</suite>
How I instantiate the drivers:
package com.github.tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.*;
public class BaseTest {
public WebDriver driver;
String url = "https://github.com/";
#Parameters("browser")
#BeforeClass
public void SetUpTests(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("ie")) {
System.setProperty("webdriver.ie.driver", ".\\drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", ".\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
//Navigate to url
driver.navigate().to(url);
//Maximize the browser window
driver.manage().window().maximize();
}
#AfterClass
public void CleanUpDriver() throws Exception {
// Quit current driver instance.
try {
driver.quit();
} catch (Exception ex) {
throw ex;
}
}
How the test run
package com.github.tests;
import com.github.pageobjects.GitHubLandingPage;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GitHubHomePageTests extends BaseTest {#Test
public void ExploreLinkTest() {
String explorePageTitle = new GitHubLandingPage(driver)
.clickGitHubExplorePage()
.getGitHubExplorerPageTitle().trim();
System.out.println(explorePageTitle);
Assert.assertEquals(explorePageTitle, "Explore GitHub");
}
}
A global Github repo is available here

Try this:
<suite name="TestingSuite" preserve-order="true" thread-count="1" verbose="10">
<test name="Test1">
<classes>
<class name="guiAndFunctianal.LoginFail" />
</classes>
</test>
<test name="Test2">
<classes>
<class name="guiAndFunctianal.LoginAsManager" />
</classes>
</test>
<test name="Test3">
<classes>
<class name="guiAndFunctianal.CreateUserTest" />
</classes>
</test>
</suite>

Close your driver before quit:
# AfterTest
public void quit() {
driver.close()
driver.quit();
}

Related

Kotlin Converted Activity code to fragment doesn't work

I'm trying to convert my activity code to a fragment so I can make a tab layout.
Now when I copied the code from my activity to the fragment I got some errors. I tried to solve them but now my code doesn't work.
What should happen is that when I tap the textview it should flip and show a random text. In the Activity it works fine but now I tried converting it to a fragment it doesn't work. Nothing happens when I tap the textview.
Even when I remove the animation, and only use the textview the random texts won't appear when clicked in it. It seams like the setOnClickListener doesn't work.
Can someone tell me what I am doing wrong?
This is my fragment code:
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
//import kotlinx.android.synthetic.main.TabStartKaartFragment.view.*
import kotlinx.android.synthetic.main.fragment_tab_start_kaart.*
class TabStartKaartFragment : Fragment() {
lateinit var front_anim: AnimatorSet
lateinit var back_anim: AnimatorSet
var isFront = false
#SuppressLint("ResourceType")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_start_kaart, container, false)
val scale = getActivity()?.applicationContext?.resources?.displayMetrics?.density
tvstartkaart.cameraDistance = 8000 * scale!!
tvstartkaartachterkant.cameraDistance = 8000 * scale
front_anim = AnimatorInflater.loadAnimator(getActivity(), R.anim.font_animation) as AnimatorSet
back_anim = AnimatorInflater.loadAnimator(getActivity(), R.anim.back_animation) as AnimatorSet
val Carts = arrayOf("" +
"Bunch of random texts",
)
tvstartkaart.setOnClickListener() {
if (isFront) {
front_anim.setTarget(tvstartkaart)
back_anim.setTarget(tvstartkaartachterkant)
front_anim.start()
back_anim.start()
isFront = false
} else {
val random = Carts.random()
tvstartkaart.setText(random)
front_anim.setTarget(tvstartkaartachterkant)
back_anim.setTarget(tvstartkaart)
front_anim.start()
back_anim.start()
isFront = true
}
};
}
This is my original activity code:
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import kotlin.random.Random
class StartKaartActivity : AppCompatActivity() {
lateinit var front_anim:AnimatorSet
lateinit var back_anim:AnimatorSet
var isFront = false
#SuppressLint("ResourceType")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start_kaart)
//Set Backbutton Bar & Logo
val display = supportActionBar
display?.title = ""
//display?.setDisplayHomeAsUpEnabled(true)
display?.setHomeAsUpIndicator(R.drawable.backarrow)
//display?.setLogo(R.drawable.logo)
display?.setIcon(R.drawable.logo);
display?.setDisplayShowHomeEnabled(true);
val scale = applicationContext.resources.displayMetrics.density
val tvstartkaart = findViewById<TextView>(com.fotf.klimaatambitiegame.R.id.tvstartkaart)
val tvstartkaartachterkant = findViewById<TextView>(com.fotf.klimaatambitiegame.R.id.tvstartkaartachterkant)
tvstartkaart.cameraDistance = 8000 * scale
tvstartkaartachterkant.cameraDistance = 8000 * scale
front_anim = AnimatorInflater.loadAnimator(applicationContext, R.anim.font_animation) as AnimatorSet
back_anim = AnimatorInflater.loadAnimator(applicationContext, R.anim.back_animation) as AnimatorSet
val Carts = arrayOf("" +
"Bunch of random texts",
)
tvstartkaart.setOnClickListener() {
if (isFront) {
front_anim.setTarget(tvstartkaart)
back_anim.setTarget(tvstartkaartachterkant)
front_anim.start()
back_anim.start()
isFront = false
} else {
val random = Carts.random()
tvstartkaart.setText(random)
front_anim.setTarget(tvstartkaartachterkant)
back_anim.setTarget(tvstartkaart)
front_anim.start()
back_anim.start()
isFront = true
}
};
}
}
This is my xml fragment file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/achtergrondnowhite"
tools:context=".TabStartKaartFragment">
<TextView
android:id="#+id/textView"
android:layout_width="372dp"
android:layout_height="62dp"
android:layout_marginTop="28dp"
android:paddingHorizontal="10dp"
android:text="Klik op de kaart om een nieuwe kaart te krijgen. \n\nGeef het goede antwoord op de vraag en verdien een houder."
android:textColor="#color/white"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvstartkaart"
android:layout_width="350dp"
android:layout_height="450dp"
android:background="#drawable/kaartstartvoorkant"
android:gravity="left|center"
android:padding="15dp"
android:paddingHorizontal="10dp"
android:text=""
android:textColor="#color/black"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.508" />
<TextView
android:id="#+id/tvstartkaartachterkant"
android:layout_width="353dp"
android:layout_height="453dp"
android:background="#drawable/kaartstartachterkant"
android:gravity="left|center"
android:padding="15dp"
android:paddingHorizontal="10dp"
android:textColor="#color/black"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
My front animation:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:valueFrom="0"
android:valueTo="180"
android:propertyName="rotationY"
android:duration="1000"
/>
<objectAnimator
android:valueFrom="1.0"
android:valueTo="0.0"
android:propertyName="alpha"
android:startOffset="500"
android:duration="1"
/>
</set>
My back animation:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:valueFrom="1.0"
android:valueTo="0.0"
android:propertyName="alpha"
android:duration="0"
/>
<objectAnimator
android:valueFrom="-180"
android:valueTo="0"
android:propertyName="rotationY"
android:repeatMode="reverse"
android:duration="1000"
/>
<objectAnimator
android:valueFrom="0.0"
android:valueTo="1.0"
android:propertyName="alpha"
android:startOffset="500"
android:duration="0"
/>
</set>

How to use groups in testNG

I am implementing groups in the testng test suite.When I run my testng suite suite,it runs only the 'FireFox' test and when I put the tag in 'Firefox' test
it runs the 'IE' test.Kindly let me know what can be the reason for this??
<groups>
<run>
<include = "smoke"/>
</run>
</groups>
<classes>
<class name = "com.asw.beginner.tests.NewTest"/>
</classes>
</test>
<test name = "FireFox" allow-return-values = "true">
<parameter name = "browser" value = "FF"/>
<classes>
<class name = "com.asw.beginner.tests.NewTest"/>
</classes>
</test>
Define your test as following:
public class Test1 {
#Test(groups = { "functest" })
public void testMethod1() {
}
#Test(groups = {"functest", "checkintest"} )
public void testMethod2() {
}
#Test(groups = { "checkintest" })
public void testMethod3() {
}
}
Then you can use xml file as following
<test name="Test1">
<groups>
<run>
<include name="functest"/>
</run>
</groups>
<classes>
<class name="example1.Test1"/>
</classes>
</test>
Above test will only run the method with group functest.
You can read more about testng from Official testng documatation
Following is example java code
import org.testng.Assert; import org.testng.annotations.Test;
public class GroupTestExample { String message = ".com"; MessageUtil messageUtil = new MessageUtil(message);
#Test(groups = { "functest", "checkintest" })
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = ".com";
Assert.assertEquals(message, messageUtil.printMessage()); }
#Test(groups = { "checkintest" })
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "tutorialspoint" + ".com";
Assert.assertEquals(message, messageUtil.salutationMessage()); }
#Test(groups = { "functest" })
public void testingExitMessage() {
System.out.println("Inside testExitMessage()");
message = "www." + "tutorialspoint"+".com";
Assert.assertEquals(message, messageUtil.exitMessage()); } }
following is Testng.xml file
<groups>
<run>
<include name = "functest" />
</run>
</groups>
<classes>
<class name = "GroupTestExample" />
</classes>
</test> </suite>

Can we pass parameters or any attributes at method level in testng.xml?

// Testng xml
<test name="Test1" preserve-order ="true">
<parameter name="deviceName_" value="aaaa"/>
<classes>
<class name="Test">
<methods>
<include name="methodName"/>
</methods>
</class>
</classes>
</test>
// Can i pass parameters at method level like i passed deviceName at test level
Actually, parameters on method level exists. Here is an example:
<suite name="my-suite" verbose="1">
<test name="my-test">
<classes>
<class name="testng.ex1.TestParams">
<methods>
<include name="m1">
<parameter name="key1" value="val1"/>
<parameter name="key2" value="val2"/>
</include>
<include name="m2">
<parameter name="key1" value="valA"/>
<parameter name="key2" value="valB"/>
</include>
</methods>
</class>
</classes>
</test>
</suite>
and the test class is,
package testng.ex1;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestParams {
#Test
#Parameters({ "key1", "key2" })
public void m1(String key1, String key2) throws Exception {
System.out.println(key1 + ", " + key2);
}
#Test
#Parameters({ "key1", "key2" })
public void m2(String key1, String key2) throws Exception {
System.out.println(key1 + ", " + key2);
}
}
another approach is to use a data-provider that fetches the keys from testng.xml. See example:
<suite name="my-suite" verbose="1">
<test name="my-test">
<classes>
<parameter name="keys" value="key1,key2,key3,key4" />
<class name="testng.ex2.TestParams" />
</classes>
</test>
</suite>
The test calss,
package testng.ex2;
import java.util.Arrays;
import java.util.List;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestParams {
#Test(dataProvider = "dp")
public void m1(Employee e) throws Exception {
System.out.println("name: " + e.getName() + ", age: " + e.getAge());
}
#DataProvider(name = "dp")
#Parameters("keys")
public Object[][] createData(ITestContext ctx) {
String keysString = ctx.getCurrentXmlTest().getLocalParameters().get("keys");
List<String> keys = Arrays.asList(keysString.split(","));
Object[][] result = new Object[keys.size()][1];
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
result[i] = new Object[] { new Employee(key) };
}
return result;
}
}
The employee class,
package testng.ex2;
public class Employee {
private final String name;
private final int age;
public Employee(String key) {
// use 'key' to lookup employee in database
name = key + "_name"; // dummy value
age = 41; // dummy value
}
String getName() {
return name;
}
int getAge() {
return age;
}
}
you can get the parameter in the before method as given below,
#BeforeMethod
#Parameters({ "key1", "key2" })
public void beforem1(String key1, String key2){
System.out.println(key1 + ", " + key2);
}

Re-Running TestNG tests not working for all the Tests

I am using IRetryAnalyzer interface to run failed test cases again. It works fine if I have only one Test in my TestNG XML file, however if I have multiple tests in my XML file it works only for the first test.
Root Cause: the retryCount for second test is set to 1, I am not sure how to reset it.
Existing open issue:
https://github.com/cbeust/testng/issues/1241
RetryAnalyzer.java
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 1;
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true;
}
return false;
}
}
AnnotationTransformer.java
public class AnnotationTransformer implements IAnnotationTransformer {
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
annotation.setRetryAnalyzer(RetryAnalyzer.class); //to enable for all the methods.
}
}
TestNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="BrowserStack" >
<listeners>
<listener class-name="uk.co.gaurang.libs.ResultListener" />
<listener class-name="uk.co.gaurang.libs.AnnotationTransformer" />
</listeners>
<test name="IPhone6S">
<classes>
<class name="uk.co.gaurang.tests.Demo"/>
</classes>
</test>
<test name="IPhone6SPlus">
<classes>
<class name="uk.co.gaurang.tests.Demo"/>
</classes>
</test>
</suite>

I am getting null pointer exception while running testng code through XML.But when running code directly its working fine

Code is Grouping in TESTNG
package testNG_annot;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestNG_grp1
{
#BeforeMethod
public void CarBM() {
System.out.println("CarBM");
}
*** // Created group car and Two wheeler//***
#Test(groups = { "Car" })
public void Sedan1() {
System.out.println("Test1-Verna");
}
#Test(groups = { "Car" })
public void Sedan2() {
System.out.println("Test2-BMW");
}
#Test(groups = { "TwoWheeler" })
public void Scooter1() {
System.out.println("Test3-ScootyPep");
}
#Test(groups = { "TwoWheeler" })
public void aScooter2() {
System.out.println("Test4-TVS");
}
}
suite.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="grp11">
<test name="group1">
<gropus>
<run>
<include name="Car"/>
</run>
</gropus>
<classes>
<class name="testNG_annot.TestNG_grp1"/>
</classes>
</test>
</suite>
Your spelling for groups tag is wrong. Change the spelling and run it again.
<groups>
<run>
<include name="Car"/>
</run>
</groups>
Form the testng.xml file as below format. Run it as testng test and you will get your test running.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1">
<test name="Test" >
<classes>
<class name="testNG_annot.TestNG_grp1" />
</classes>
</test>
</suite>
Keep this on top in your xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >