#After and #Before annotation is not executing second method - java

I have declared 2 methods #after annotation but it will execute only the first method, it does not allow me to execute the second method. Please have a look at the below code
I want to execute 1 method every time for the exit of the browser.
I want to execute the second method for failed test cases.
#Before
public void databaseLoading(Scenario scenario) {
//System.out.println("Test Environment Set Up");
System.out.println("\n------------------------------------------------ TEST ENVIRONMENT SET UP ------------------------------------------------------------------------------\n");
System.out.println("Executing Scenario :-> " + scenario.getName());
}
#After
public void browserTearDown()
{
System.out.println("End the browser");
driver.close();
}
public void Screenshot(Scenario scenario) {
// take the screenshot at the end of every test
String location = ".\\target\\TakeScreenshot";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss", Locale.ENGLISH);
Date date = new Date();
File scrFile =
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// now save the screenshto to a file some place
if (scenario.isFailed()) {
try {
FileUtils.copyFile(scrFile, new File(location + "\\" + dateFormat.format(date) + ".png"));
System.out.println("Screenshot saved");
} catch (IOException e) {
System.out.println("Error in taking Screenshot --> " + e);
}
}
}
Method 'Screenshot(cucumber.api.Scenario)' is never used. This error message comes for the second method.

You only tagged browserTearDown() method.
Add the #After tag to the Screenshot() method, as well:
#After
public void browserTearDown()
{
System.out.println("End the browser");
driver.close();
}
#After
public void Screenshot(Scenario scenario) {
...
}

Related

How to attach SOFTASSERT screenshots to Allure report?

I am a manual tester learning Selenium+Java at the moment. Thanks to a lot of brilliant answers at Stack Overflow, I managed to take screenshot when SoftAssert fails, but I'm now struggling with attaching these screenshot on Allure report. Can someone tell me what to add to my code to have these screenshot attached to the Allure report? Many thanks!!
//Override my onAssertFailure:**
public class CustomSoftAssert extends SoftAssert{
#Override
public void onAssertFailure(IAssert<?> assertCommand, AssertionError ex)
{
WebDriver driver = TestBase.getDriver1();
Reporting.takeScreenshot(driver);
}
//takeScreenshot method:
public static void takeScreenshot(WebDriver driver) {
try
{
TakesScreenshot ts=(TakesScreenshot) driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./screenshots/"+System.currentTimeMillis()+".png"));
System.out.println("Screenshot taken");
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}
//onTestFailure method in AllureTestListener**
#Override
public void onTestFailure(ITestResult iTestResult) {
System.out.println("I am in onTestFailure method " + getTestMethodName(iTestResult) + " failed");
Object testClass = iTestResult.getInstance();
WebDriver driver = TestBase.getDriver1();
// Allure ScreenShotRobot and SaveTestLog
if (driver instanceof WebDriver) {
System.out.println("Screenshot captured for test case:" + getTestMethodName(iTestResult));
saveScreenshotPNG(driver);
}
// Save a log on allure.
saveTextLog(getTestMethodName(iTestResult) + " failed and screenshot taken.");
}```

how can I close browser after reach scenarion in cucumber by java , my code is not working

I have issue with cucumber hooks
I want to close browser after each scenario , in the following code when I run my scenarios , all of them will run in the same browser.
Could you please check my code and tell me what's wrong ??
Note: that i didn't write any thing in after and initialize value for dunit is false
#Before
public void beforeAll(Scenario Scenario) {
if (!dunit) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
} catch (Exception e) {
}
System.out.println("Scenario " + Scenario.getName()+ " has been finished" );
PageFactory.instance().getWebDriver();
PageFactory._driver.quit();
}
});
;
System.out.println("Scenario " + Scenario.getName()+ " has been started");
dunit = true;
}
}

How to do JUnit test from only one GUI?

I wrote some JUnit test cases at Winium which is nearly same as Selenium for Calculator. My problem is with every test a new calculator.exe is started but I want to do all the test for the same calculator.exe but I also want to seperate the JUnit test. Below you can see my code:
public class calculatorTest {
#Test
public void additionTest() throws MalformedURLException, InterruptedException {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("C:\\Windows\\System32\\calc.exe");
WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999") , option);
Thread.sleep(2000);
driver.findElement(By.name("Seven")).click();
driver.findElement(By.name("Plus")).click();
driver.findElement(By.name("Eight")).click();
driver.findElement(By.name("Equals")).click();
String output = driver.findElement(By.id("CalculatorResults")).getAttribute("Name");
System.out.println("Result is " + output);
assertEquals("Display is 15", output);
}
#Test
public void subtractionTest() throws MalformedURLException, InterruptedException {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("C:\\Windows\\System32\\calc.exe");
WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999") , option);
Thread.sleep(2000);
driver.findElement(By.name("Nine")).click();
driver.findElement(By.name("Minus")).click();
driver.findElement(By.name("Eight")).click();
driver.findElement(By.name("Equals")).click();
String output = driver.findElement(By.id("CalculatorResults")).getAttribute("Name");
System.out.println("Result is " + output);
}
You can add a configuration method to your test class, which is a part of JUnit
#BeforeClass
public void openCalculator() {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("C:\\Windows\\System32\\calc.exe");
WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999") , option);
Thread.sleep(2000);
}

Webdriver not closing after driver.quit has been called

I am running tests with WebDriver, when a test fails, the browser does not close. On a Windows machine this is a huge problem because I then have several instances of the Firefox still running in the background. Kindly advise
Here's the code :
public static WebDriver driver;
private String sTestCaseName;
#BeforeMethod
public void beforeMethod() throws Exception {
DOMConfigurator.configure("log4j.xml");
sTestCaseName = Constant.Login_Name;
Log.startTestCase(sTestCaseName);
new BaseClass(driver);
}
#Test(description = "Login", enabled = true)
public void TestLogin_Success() throws Exception {
try {
driver = new FirefoxDriver();
LoginBuilder.Execute(driver);
Log.info("Successfully Login!");
} catch (Exception e) {
Log.error(e.getMessage());
throw (e);
}
}
#Test(description = "Login_Failed", enabled = true)
public void TestLogin_Failed() throws Exception {
try {
driver = new FirefoxDriver();
LoginBuilder.Execute_Failed(driver);
Log.info("Unsuccessfully Login!");
} catch (Exception e) {
Log.error(e.getMessage());
throw (e);
}
}
#AfterMethod
public void afterMethod() {
Log.endTestCase(sTestCaseName);
driver.close();
}
Add finally block to your try catch block.
Close the WebDriver there.
Sample code snippet
try {
....
....
} catch(Exception e) {
....
....
} finally {
....
driver.close();
}
More info on Dispose, Close and Quit - Difference between webdriver.Dispose(), .Close() and .Quit()
Call driver.quit() instead of driver.close()
#AfterMethod
public void afterMethod() {
Log.endTestCase(sTestCaseName);
driver.quit();
}
Why don't you try to use #AfterClass

TestNG handling external system dependency, clarification needed

What changes do i need to make to the following please?
I'd like make sure that testInsert method to only run when testInternalAccess passes and testInternalAccess not count as a failure.
#Test
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
#Test(groups = "database", dependsOnMethods = "testInternalAccess")
public void testInsert() {
// some code
}
In the above example:
testInternalAccess runs, fails and being reported as a failed test
testInsert runs and fails
Or, using creator's of TestNG example
#Test
public serverStartedOk() {}
#Test(dependsOnMethods = { "serverStartedOk" })
public method1() {}
How will method1 know whether server actually started ok? How will serverstartedOk communicate to the world it's state?
Based on the discussion we had above, following is the brief summary.
As you wish to run the method testinternalAcecess before you run all the tests in the class use #BeforeClass
#BeforeSuite
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
The method runs only once and before all tests run in the suite! And you test method would be some thing as below
#Test(groups = "database")
public void testInsert() {
// some code
}
Bingo and this would work!

Categories