Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parameter 'browser' is required by @Configuration on method setUp but has not been marked @Optional or defined #10

Open
meetparag81 opened this issue Feb 28, 2018 · 33 comments

Comments

@meetparag81
Copy link

Hello,
I am getting "Parameter 'browser' is required by @configuration on method setUp but has not been marked @optional or defined" message while running my test class
I have extended my base class to test class as well as I have added browser and url values in testng xml
Please refer code below

Base class
public class Baseclass_1
{
public static WebDriver driver;

@Parameters({"browser","url"})
@BeforeClass
public  void setUp(String browser,String url)
{
	if(browser.equalsIgnoreCase("firefox"))
	{
		System.setProperty("webdriver.gecko.driver","G:\\Javaprogramming\\Selenium\\Selenium Setup\\geckodriver.exe");
		driver=new ChromeDriver();
		
	}
	else if(browser.equalsIgnoreCase("chrome"))
	{
		
		
	}
	driver.get(url);
	driver.manage().window().maximize();
	
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	
	
}

@AfterClass
public void tearDown()
{
	driver.quit();
		
}

===================================================================
Test class
public class FBTestnew extends Baseclass_1
{
WebDriver driver;

@Test	
public void LogintoFB()
{
	
	// Baseclass_1.setUp("firefox","https://www.facebook.com/");
	FBHome FB_Hpme =PageFactory.initElements(driver, FBHome.class);
	FB_Hpme.LogintoFB("username", "password");
	
}

}

Testng xml

	<classes>
		<class name="Com.Browser.Baseclass_1" />
	</classes>
</test>
But running a test class or testng xml The browser is not launched. Execuring RunAs TestNG class from test class following error seen

FAILED CONFIGURATION: @BeforeClass setUp
org.testng.TestNGException:
Parameter 'browser' is required by @configuration on method setUp but has not been marked @optional or defined

Where as on running testng by executing Run As TestNG Suite, following error seen.
[RemoteTestNG] detected TestNG version 6.8.0
[TestNG] Running:
G:\Javaprogramming\Maven2\testng.xml

Parameterization Test Suite
Total tests run: 0, Failures: 0, Skips: 0

Can Anyone help me?

@bhange24
Copy link

bhange24 commented Jun 6, 2018

Hi meetparag81,
Your are getting this error because you must be executing Baseclass_1.java file. You need to execute Testng XML file.

@mgmwalkerp07
Copy link

Thank you!

@abha-singh
Copy link

Hey, I am also getting this error even I am executing my Testng.xml file.
Please help.

image

@lucky17166
Copy link

lucky17166 commented Jun 24, 2019

Hi,
Since you are sending browser and url parameters, you need to also add Parameter tag in Testng.xml file after "test" tag.

<parameter name="browser" value="chrome"/>
<parameter name="url" value="https://www.google.com"/>

Please find below code format in Testng.xml file:

<suite name="Sample suite">
  <test thread-count="5"
   name="Test `name">`
   <parameter name="browser" value="chrome"/>
   <parameter name="url" value="https://www.google.com"/>
   <classes>
      <class name="Packagename.Classname"/> 
    </classes>
   </test>
   </suite>

@deven-s
Copy link

deven-s commented Nov 20, 2019

@meetparag81 In Testng.xml file use standartd DTD type its causing the problem. In my case I was getting same problem as mentioned in the main question, Testng.xml file was generated at runtime and it was missing the below DTD after adding this to the Testng.xml the problem gone away

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

@KaustuvTalukdar
Copy link

Hey, I am also getting the same error though everything is perfect as mentioned by you guys!!

@RohanImmanuel
Copy link
Contributor

@KaustuvTalukdar can you share the code snippet/repo for this

@KaustuvTalukdar
Copy link

Hey @RohanImmanuel, thanks a lot for answering. I have got my issue resolved now!! Many thanks.

@AutomationBatch2019
Copy link

Hey, I am also getting the same error though everything is perfect. Please Help.

@wati123321
Copy link

Hi @AutomationBatch2019, can you share the code snippet/repo for your test?

@AutomationBatch2019
Copy link

public static WebDriver driver;

@BeforeMethod
@Parameters({"browser", "baseUrl"})
public void setUp(String browserName, String url)
{
	if (browserName.equalsIgnoreCase("chrome"))
	{
		System.setProperty("webdriver.chrome.driver", "/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/chromedriver");
		driver= new ChromeDriver();
		Reporter.log("Chrome Launched", true);
	}
	else if(browserName.equalsIgnoreCase("FireFox"))
	{
		System.setProperty("webdriver.gecko.driver","/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/geckodriver");
		driver= new FirefoxDriver();
		Reporter.log("Firefox Launched", true);	
	}

TestNG.xml

<classes>
  <class name="scriptTest.LoginPageTest"/>
</classes>

Hi @AutomationBatch2019, can you share the code snippet/repo for your test?

i am using this with Maven

@RohanImmanuel
Copy link
Contributor

Hi @AutomationBatch2019,

From the shared snippet, it looks like you are having issues initiating browser drivers on your local system.

System.setProperty("webdriver.chrome.driver", "/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/chromedriver");

System.setProperty("webdriver.gecko.driver","/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/geckodriver");

This repository contains sample code to run tests on BrowserStack's cloud infrastructure using TestNG.

You will find it more helpful to raise a new issue here:
https://github.com/cbeust/testng/issues

@AutomationBatch2019
Copy link

Hi @AutomationBatch2019,

From the shared snippet, it looks like you are having issues initiating browser drivers on your local system.

System.setProperty("webdriver.chrome.driver", "/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/chromedriver");

System.setProperty("webdriver.gecko.driver","/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/geckodriver");

This repository contains sample code to run tests on BrowserStack's cloud infrastructure using TestNG.

You will find it more helpful to raise a new issue here:
https://github.com/cbeust/testng/issues

Hey, Rohanlmmanuel my issue has been resolved

@AutomationBatch2019
Copy link

Hi @AutomationBatch2019,
From the shared snippet, it looks like you are having issues initiating browser drivers on your local system.

System.setProperty("webdriver.chrome.driver", "/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/chromedriver");

System.setProperty("webdriver.gecko.driver","/home/ambrish/Lockdown_Tets/SeleniumPractice/drivers/geckodriver");

This repository contains sample code to run tests on BrowserStack's cloud infrastructure using TestNG.
You will find it more helpful to raise a new issue here:
https://github.com/cbeust/testng/issues

Hey, Rohanlmmanuel my issue has been resolved

Thankyou So much

@RohanImmanuel
Copy link
Contributor

@francisf this issue can be closed

@RohanImmanuel
Copy link
Contributor

Hi @ShorouqElrakhawy

I would like to reiterate what I had said earlier on this thread here: #10 (comment)

This repository contains sample code to run tests on BrowserStack's cloud infrastructure using TestNG.

From your shared screenshots, it looks like you are having issues initiating browser drivers on your local system.

You will find it more helpful to raise a new issue here:
https://github.com/cbeust/testng/issues

@anixumoh
Copy link

@RohanImmanuel Please i need your help i am having the same here as mentioned above kindly help.
issue

@anixumoh
Copy link

My Xml file

<test name="Banking Test">
    <parameter name ="browser" value="chrome"/>
    <clasess>
        <class name ="com.inetBankingTestCases.LoginTest_001"/>

    </clasess>
</test>

@RohanImmanuel
Copy link
Contributor

RohanImmanuel commented Jun 22, 2020

Hi @anixumoh,

Could you try executing the TestNG XML file in place of the ".java" file, as suggested by @bhange24 here

If you continue to encounter the error, please do share a sample repo to debug this further.

@Sjsantoshi
Copy link

Hey @bhange24 @anixumoh
Reply to your comment: Your are getting this error because you must be executing Baseclass_1.java file. You need to execute Testng XML file.

Why is it so? If I run through testNG XML file it works fine but does not work when I run through Class.java file. But it should be working in both the cases right?

@anixumoh
Copy link

@RohanImmanuel i have executed the XML file too error still persist.. i have shared my sample repo .. Hope to get this sorted.. Thanks

@anixumoh
Copy link

Hey @bhange24 @anixumoh
Reply to your comment: Your are getting this error because you must be executing Baseclass_1.java file. You need to execute Testng XML file.

Why is it so? If I run through testNG XML file it works fine but does not work when I run through Class.java file. But it should be working in both the cases right?

You are right its should run irrespective where you execute it. because its runs with TestNG

1 similar comment
@anixumoh
Copy link

Hey @bhange24 @anixumoh
Reply to your comment: Your are getting this error because you must be executing Baseclass_1.java file. You need to execute Testng XML file.

Why is it so? If I run through testNG XML file it works fine but does not work when I run through Class.java file. But it should be working in both the cases right?

You are right its should run irrespective where you execute it. because its runs with TestNG

@Sjsantoshi
Copy link

@anixumoh How to run the same from class file then? It is still not working for me. I keep getting this error when run from java file
image
but works perfectly fine when ran from xml file.

@RohanImmanuel
Copy link
Contributor

RohanImmanuel commented Jun 22, 2020

@anixumoh this repo implements a custom BrowserStackTestNGTest class from which all the tests extend. This class has the function setUp configured as the "@BeforeMethod" this function requires two parameters "config_file" and "environment" which are defined in the *.testng.xml files and hence if you try to execute the java files directly you will encounter the error as mentioned above.

@BrahmendraJayaraju
Copy link

BrahmendraJayaraju commented May 6, 2021

i am getting this error org.testng.TestNGException:
Parameter 'browser' is required by BeforeSuite on method preconditionSetBrowser but has not been marked @optional or defined
in

My base class

public class AdminBaseControl
{
String chrome_key="webdriver.chrome.driver";

String chrome_value="C:\\Automation\\Digital\\Drivers\\chromedriver.exe";

String Gecko_key="webdriver.gecko.driver";

String Gecko_value="C:\\Automation\\Digital\\Drivers\\geckodriver.exe";

String Edge_key="webdriver.edge.driver";

String Edge_value="C:\\Automation\\Digital\\Drivers\\msedgedriver.exe";


public static WebDriver driver;


public static String setUpData = "C:\\Automation\\Digital\\TestEnviornmentSetUp\\BasicTestSetUp.properties";


public WebDriver getWebDriver()
{
    return driver;
}


@Parameters({"browser"})
@BeforeSuite
public void preconditionSetBrowser(String browser) throws Exception
{
	
	if(browser.equalsIgnoreCase("chrome"))
	{

System.setProperty(chrome_key,chrome_value);

		driver = new ChromeDriver();
	
		
	}
	
	else if(browser.equalsIgnoreCase("firefox"))
	{
		System.setProperty(Gecko_key,Gecko_value);
		driver = new FirefoxDriver();
		
	}
	
			else if(browser.equalsIgnoreCase("Edge"))
			{
				
				System.setProperty(Edge_key,Edge_value);
				
				driver = new EdgeDriver();
			}
	
	else
	{
		
		throw new Exception("Browser is not correct");
	}
	
	
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

}

my testclass

public class TestLoginPages extends AdminBaseControl
{

LoginPage loginPage = new LoginPage(driver);

public static String filepath = "/TestEnviornmentSetUp/BasicTestSetUp.properties";


@Test(priority = 0)
public void ValidLoginPage() throws Exception
{
    AdminBaseControl.createTestName("Validate Login Page", "User should be able to login");
    
    if(WebUtilityKeys.readPropertyFiles(filepath,"QA_ENVIRONMENT").equals("Yes".trim())) 
    {
        loginPage.goTOAdminPage(WebUtilityKeys.readPropertyFiles(filepath, "QA_ADMIN"));
        
        loginPage.enterUserName("subject","53637");
        loginPage.clickToLoginButton("post-button");
        loginPage.enterPassWord("password","abc");
        loginPage.clickToLoginButton("remember-me-login-button");
    }
    
    
    
    else if(WebUtilityKeys.readPropertyFiles(filepath,"UAT_ENVIRONMENT").equals("Yes".trim()))
    {
        loginPage.goTOAdminPage(WebUtilityKeys.readPropertyFiles(filepath, "UAT_ADMIN"));
        
        loginPage.enterUserName("subject","1234");
        loginPage.clickToLoginButton("post-button");
        loginPage.enterPassWord("password","abdc");
        loginPage.clickToLoginButton("remember-me-login-button");

    }
}

}

my testng.xml

@Vanda240
Copy link

parameter 'browser' is required by beforeclass on method setup but has not been marked @optional or defined. Please help me.

This is my Base Class

package testBase;

public class BaseClass
{
public WebDriver driver;
public Logger logger;
public ResourceBundle rb;

@BeforeClass(groups= {"regression","master","sanity"}) 
@Parameters({"browser"})

public void setup(String br)
{
	//Loading config.properties
	rb=ResourceBundle.getBundle("config");
	
	//Logging
	
	logger=LogManager.getLogger(this.getClass()); //'this' means current case class(TC_001_AccountRegistration) '.getClass()' means current class name.
	
	
	//driver instance
	if(br.equals("chrome"))
	{
	WebDriverManager.chromedriver().setup(); //launch browser
	driver=new ChromeDriver();
	logger.info("Launched Chrome Browser");
	}
	else if(br.equals("edge"))
	{
		WebDriverManager.edgedriver().setup(); //launch browser
		driver=new EdgeDriver();
		logger.info("Launched Edge Browser");
	}
	else if(br.equals("firefox"))
	{
		WebDriverManager.firefoxdriver().setup(); //launch browser
		driver=new FirefoxDriver();
		logger.info("Launched Firefox Browser");
	}
	
	driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
}

@AfterClass(groups= {"regression","master","sanity"}) 
public void tearDown()
{
driver.close();
}


public String randomestring() 
{
	String generatedString = RandomStringUtils.randomAlphabetic(5); //generate random string
	return (generatedString);
}

public int randomeNumber() 
{
	String generatedString2 = RandomStringUtils.randomNumeric(5); 
	return (Integer.parseInt(generatedString2));
}

public void captureScreen(WebDriver driver, String tname) throws IOException {
	TakesScreenshot ts = (TakesScreenshot) driver;
	File source = ts.getScreenshotAs(OutputType.FILE);
	File target = new File(System.getProperty("user.dir") + "\\screenshots\\" + tname + ".png");
	FileUtils.copyFile(source, target);
}

}

This is my Test Class

package testCases;

import java.io.IOException;

import org.testng.Assert;
import org.testng.annotations.Test;
import pageObjects.AccountRegistrationPage;
import pageObjects.HomePage;
import testBase.BaseClass;

public class TC_001_AccountRegistration extends BaseClass
{
@test(groups= {"regression","master"})
public void test_account_Registration() throws IOException
{
logger.info("Starting TC_001_AccountRegistration");

	try
	{
	driver.get(rb.getString("appURL"));
	driver.manage().window().maximize();
	logger.info("Home Page Displayed");
	
	HomePage hp=new HomePage(driver);
	hp.clickMyAccount();
	logger.info("Clicked on My Account");
	
	hp.clickRegister();
	logger.info("Clicked on Register");
	
	AccountRegistrationPage regpage=new AccountRegistrationPage(driver);
	
	regpage.setFirstName("Henry");
	logger.info("Provided First Name");
	
	regpage.setLastName("Fox");
	logger.info("Provided Last Name");
	
	regpage.setEmail(randomestring()+"@gmail.com");
	logger.info("Provided Email");
	
	regpage.setTelephone("2345678901");
	logger.info("Provided Phone Number");
	
	regpage.setPassword("abcdgf");
	logger.info("Provided Password");
	
	regpage.setConfirmPassword("abcdgf");
	logger.info("Provided Confirmed Password");
	
	regpage.setPrivacyPolicy();
	logger.info("Set Private Policy ");
	
	regpage.clickContinue();
	logger.info("Clicked on Continue");
	
	String confmsg=regpage.getConfirmationMsg();
	
	if(confmsg.equals("Your Account Has Been Created!"))
	{
		logger.info("Account Registration Success");
		Assert.assertTrue(true);
	}
	else
	{
		logger.error("Account Registration Failed");
		captureScreen(driver,"test_account_Registration"); 
		Assert.assertTrue(false);
	}
	
	
}
	catch(Exception e)
	{
		logger.fatal("Account Registration Failed");
		captureScreen(driver,"test_account_Registration");
		Assert.fail();
	}
	
	logger.info("Finished TC_001_AccountRegistration");
	
}

}

This is my Testng.xml

<listeners>
	<listener class-name="utilities.ExtentReportManager"/>
</listeners>

<test name="OpenCartTests">
	
	<parameter name="browser" value="chrome"/>

	<classes>
		
		<class name="testCases.TC_001_AccountRegistration"/> 
        
             
                </classes>
	
</test>

@sharutkarsh
Copy link

hey @Vanda240

could you please refer to this solution - #10 (comment)

Also, if that does not work out please reach out to - "https://www.browserstack.com/contact?ref=footer"

@Vanda240
Copy link

I refer to that solution but it didn't work.

@agrawalkartik136
Copy link

I am also facing the same problem. Can anyone help please!
UITest.startBrowser » TestNG
Parameter 'Browser' is required by @test on meth

@grandEL-dsouza
Copy link

Hey @agrawalkartik136

Can you please share a sample code snippet of the test you are trying to execute.

Thanks.

@RucheeSadani16
Copy link

HI Guys,

I facing the same error in my ci/cd pipeline

image

Can someone please let me know the solution

Below is my playwright.yml file

name: Website Automation
on:

schedule:

# Run this workflow at 3:00 UTC (7:00 GST) from Monday till Friday

- cron: '0 3 * * 1-5'

workflow_dispatch:
inputs:
environment:
description: 'Environment to run tests against'
required: true
type: choice
options:
- stg
- uat
default: stg
jobs:
build:
env:
environment: ${{ github.event.inputs.environment }}
run: ${{ github.event.inputs.run }}
runs-on: ubuntu-latest
steps:
- name: Setting up test environment variable
run: |
echo 'environment=${{ github.event.inputs.environment }}' >> $GITHUB_ENV

  - name: Checking out the repo
    uses: actions/checkout@v3

  - name: Set up JDK 17
    uses: actions/setup-java@v3
    if: always()
    with:
      java-version: '17'
      distribution: 'temurin'
      cache: maven

  - name: Cache local Maven repository
    uses: actions/cache@v3
    if: always()
    with:
      path: ~/.m2/repository
      key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
      restore-keys: |
        ${{ runner.os }}-maven-

  - name: Test using Maven
    if: always()
    run: |
      mvn clean test -DENV=${{ env.environment }}

  - name: Check files
    if: always()
    run: |
      ls   

  - uses: actions/upload-artifact@master
    if: always()
    continue-on-error: true
    with:
      name: allure-results
      path: allure-results
      retention-days: 10

  - name: Get Allure history
    uses: actions/checkout@v3
    if: always()
    continue-on-error: true
    with:
      ref: gh-pages
      path: gh-pages

  - name: Test marketplace action
    uses: simple-elf/allure-report-action@master
    if: always()
    id: allure-report
    with:
      allure_results: allure-results
      gh_pages: gh-pages
      allure_report: allure-report
      allure_history: allure-history
      keep_reports: 30

  - name: Deploy report to Github Pages
    if: always()
    uses: peaceiris/actions-gh-pages@v3
    with:
      PERSONAL_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      PUBLISH_BRANCH: gh-pages
      PUBLISH_DIR: allure-history

  - name: Send custom JSON data to Slack
    id: slack
    uses: slackapi/[email protected]
    if: always()
    with:
      payload-file-path: "./target/slack-message.json"
    env:
      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
      SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK

@Browseutkarsh
Copy link

Hi @RucheeSadani16

Kindly raise a support ticket by sending an email to [[email protected]]or via Contact Us (https://www.browserstack.com/contact).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests