Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

selenium - Saving java robot screenshot into testng listener with Extent Reports

I have a test method below which checks for empty password:

@Test(priority = 4,description = "Empty password validation")
public void emptyPassword(Method method, ITestContext context) {
        ExcelData ex = new ExcelData();
        try {
            ISuite suite = context.getSuite();
            String env = (String)suite.getAttribute("Env");

            String [] envLinks = ex.getEnvLinks(env);
            homePage.loadLMSLoginPage(envLinks[0]);
            ExtentTestManager.startTest(method.getName(), "Empty Password Validation");
            loginPage
                    .verifyEmptyPassword("USERNAME","",context);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

This is the password verify method, as the system will display a pop up alert when the password is empty, selenium webdriver cannot take a screenshot, hence I'm using the robot framework. I'm trying to pass this screenshot into my Listener class through ITestContext below:

public LoginPage verifyEmptyPassword(String id, String pswd, ITestContext context) throws AWTException {

        try {

            writeText(userId, id);
            writeText(userPwd, pswd);
            click(logInButtonId);
            Alert passwordAlert = driver.switchTo().alert();
            String passText = passwordAlert.getText();

            Robot robot = new Robot();
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage image = robot.createScreenCapture(screenRect);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            context.setAttribute("PasswordAlert", passText);
            ImageIO.write(image, "PNG", out);
            out.flush();
            byte[] encodeBase64 = Base64.encodeBase64(out.toByteArray());
            context.setAttribute("AlertScreenshot", encodeBase64);

            passwordAlert.accept();

            Assert.assertTrue(passText.contains("Enter Password !"));
        }catch (IOException e){
            e.printStackTrace();;
        }
        return this;
    }

In my listener class, in my onTestSuccess method, if it detects the method is 'emptyPassword' as per the testname, it will save the screenshot differently in another method getPasswordAlert() in another class which my Listener class is extending:

public void onTestSuccess(ITestResult iTestResult) {
        System.out.println("Test" + getTestMethodName(iTestResult) + " passed");
        //ExtentReports log operation for passed tests.
        Object testClass = iTestResult.getInstance();
        ITestContext context = iTestResult.getTestContext();
        ExtentTest extent = ExtentTestManager.getTest();
        WebDriver webDriver = ((BaseTest) testClass).getDriver();
        String base64Screenshot = "data:image/png;base64," + ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BASE64);
          if (getTestMethodName(iTestResult).equals("emptyPassword")) {
            getPasswordAlert(context,extent);
        } else {
            ExtentTestManager.getTest().log(LogStatus.PASS, "Test passed",
                    ExtentTestManager.getTest().addBase64ScreenShot(base64Screenshot));
        }
    }

This is where I try to get the screenshot from the context and save it, but it comes out blank like below in ExtentReports, have been trying to debug this but can't find an answer. Could anyone assist?

public void getPasswordAlert(ITestContext context, ExtentTest extent) {
        String message = (String) context.getAttribute("PasswordAlert");
        byte [] imgByte = (byte[]) context.getAttribute("AlertScreenshot");
        String img = new String(imgByte);
        extent.log(LogStatus.PASS, "Test passed, alert message:" + message,
                extent.addBase64ScreenShot(img));

    }

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a new class (screenshot) with method "captureScreenshot" to take screenshot

 try{
            projectPath = System.getProperty("user.dir");
            TakesScreenshot ts=(TakesScreenshot)driver;
            File source=ts.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(source, new File("./screenshots/"+ screenshotName+".png"));
            System.out.println("Screenshot taken successfully");
            }
            catch (Exception e){
                System.out.println("Exception while taking screenshot "+e.getMessage());
            }
} 

and then call that class in your test case

screenshot.captureScreenshot();
test1.log(Status.FAIL, "Test failed.", MediaEntityBuilder.createScreenCaptureFromPath(projectPath+ "/screenshots/imagename.png").build());

Hope this will help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...