Как сделать снимок экрана браузера chrome, если мои тесты не пройдены и до закрытия браузера chrome (@After) - PullRequest
1 голос
/ 23 января 2020

Я запустил этот код и снимок экрана снимается после закрытия браузера chrome (@After) Если я закомментирую CloseBrowser (); снимок экрана снимается, но браузер Chrome остается открытым. Я хочу, чтобы скриншот был снят при неудачном тесте, а затем закройте браузер.

в итоге Снимок экрана в настоящее время захватывает после закрытия браузера, что является просто пустым. до закрытия браузера

Спасибо

public class TestClass extends classHelper//has BrowserSetup(); and CloseBrowser(); {

 @Rule
 public ScreenshotTestRule my = new ScreenshotTestRule(); 

 @Before
 public void BeforeTest()
 {
      BrowserSetup();// launches chromedriver browser
 }

 @Test
 public void ViewAssetPage() 
 {
     //My test code here//And want to take screenshot on failure
 }

 @After
 public void AfterTest() throws InterruptedException
 {
      CloseBrowser();//closes the browser after test passes or fails
 }
}

class ScreenshotTestRule implements MethodRule {
    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    statement.evaluate();
                } catch (Throwable t) {
                    captureScreenshot(frameworkMethod.getName());
                    throw t; // rethrow to allow the failure to be reported to JUnit
                }
            }
            public void captureScreenshot(String fileName) {
                try {
                    new File("target/surefire-reports/").mkdirs(); // Insure directory is there
                    FileOutputStream out = new FileOutputStream("target/surefire-reports/screenshot-" + fileName + ".png");
                    out.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
                    out.close();
                } catch (Exception e) {
                    // No need to crash the tests if the screenshot fails
                }
            }
        };
    }
}

Ответы [ 3 ]

0 голосов
/ 23 января 2020

Итак, я нашел способ реализовать скриншоты. Я создал метод, который сделает снимок экрана. Я попытался обойти свой тестовый код, поймать исключение и вызвать метод, чтобы сделать скриншот.

       public class TestClass extends classHelper//has BrowserSetup(); and CloseBrowser(); {`

     @Rule
     public ScreenshotTestRule my = new ScreenshotTestRule(); 

     @Before
     public void BeforeTest()
     {
          BrowserSetup();// launches chromedriver browser
     }

     @Test
     public void ViewAssetPage() 
     {
       try
      {
        //My test code here//And want to take screenshot on failure
      }
      catch(Exception e)
      {
          //print e
          takeScreenShot();
      }
     }

     @After
     public void AfterTest() throws InterruptedException
     {
          CloseBrowser();//closes the browser after test passes or fails
     }
    }

////////////////// //////////////////////////

void takeScreenShot()
        {
            try
            {
                int num = 0;
                String fileName = "SS"+NAME.getMethodName()+".png";//name of file/s you wish to create
                String dir = "src/test/screenshot";//directory where screenshots live

                new File(dir).mkdirs();//makes new directory if does not exist
                File myFile = new File(dir,fileName);//creates file in a directory n specified name

                while (myFile.exists())//if file name exists increment name with +1
                {
                   fileName = "SS"+NAME.getMethodName()+(num++)+".png";
                   myFile = new File(dir,fileName);
                }

                FileOutputStream out = new FileOutputStream(myFile);//creates an output for the created file
                out.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));//Takes screenshot and writes the screenshot data to the created file
                //FileOutputStream out = new FileOutputStream("target/surefire-reports/" + fileName);
                out.close();//closes the outputstream for the file
            }
            catch (Exception e)
            {
                // No need to crash the tests if the screenshot fails
            }
0 голосов
/ 24 января 2020

Это может помочь: https://github.com/junit-team/junit4/issues/383

Порядок выполнения правил изменился с новым «TestRule»

0 голосов
/ 23 января 2020

Вы можете реализовать прослушиватели TestNG для выполнения кода перед тестом или после теста, а также в случае неудачного или успешного выполнения теста и т. Д. c.

Реализуйте его, как показано ниже, и поместите свой скриншот в метод, который я показал

public class Listeners implements ITestListener {

Methods…
And put the screenshot code inside the method below:

@Override
    public void onTestFailure(ITestResult result) {
        code for screenshot
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...