#java #testng
Вопрос:
Я провожу некоторые тесты с использованием Java TestNG, но я заметил, что тесты не выполняют @AfterTest
метод. Браузер остается открытым, когда выполняются другие тесты (когда он запускает первый тест CreateNewUserWithValidData()
, этот @AfterTest
метод не вызывает , что приводит к сбою других тестов). Мне нужно, чтобы каждый тест вызывал этот @AfterTest
метод.
Мой testng.xml файл имеет следующую структуру:
lt;suite name="Sample Tests" verbose="1" gt; lt;listenersgt; lt;listener class-name="Utilities.Listeners.TestListener"gt;lt;/listenergt; lt;listener class-name="Utilities.Listeners.AnnotationTransformer"gt;lt;/listenergt; lt;/listenersgt; lt;test name="Regression" gt; lt;classesgt; lt;class name="Tests.AutomationPracticesTests"gt; lt;methodsgt; lt;include name="CreateNewUserWithValidData" /gt; lt;include name="LoginWithAValidUser" /gt; lt;include name="LoginWithAnInvalidUser" /gt; lt;/methodsgt; lt;/classgt; lt;/classesgt; lt;/testgt; lt;/suitegt;
Мой базовый класс выглядит так.-
public class BaseTest { protected String baseURL; protected WebDriver driver; protected WebDriverWait wait; protected APAuthenticationPage apAuthenticationPage; protected APCreateAccountPage apCreateAccountPage; protected APHomePage apHomePage; protected APMyAccountPage apMyAccountPage; protected APShoppingCartAddressesPage apShoppingCartAddressesPage; protected APShoppingCartOrderConfirmationPage apShoppingCartOrderConfirmationPage; protected APShoppingCartOrderSummaryBankwirePage apShoppingCartOrderSummaryBankwirePage; protected APShoppingCartPaymentMethodPage apShoppingCartPaymentMethodPage; protected APShoppingCartShippingPage apShoppingCartShippingPage; protected APShoppingCartSummaryPage apShoppingCartSummaryPage; public WebDriver getDriver() { return driver; } @BeforeTest(alwaysRun = true) public void setUp() { Log.info("I am in Before Method! Test is starting!"); driver = WebDriverFactory.getDriver(BrowserType.Chrome); wait = new WebDriverWait(driver, 10); driver.manage().window().maximize(); } @BeforeMethod public void initSetup() { String propertiesFile = "data.properties"; PropertyReader propertyReader = new PropertyReader(); apAuthenticationPage = new APAuthenticationPage(driver); apCreateAccountPage = new APCreateAccountPage(driver); apHomePage = new APHomePage(driver); apMyAccountPage = new APMyAccountPage(driver); apShoppingCartAddressesPage = new APShoppingCartAddressesPage(driver); apShoppingCartOrderConfirmationPage = new APShoppingCartOrderConfirmationPage(driver); apShoppingCartOrderSummaryBankwirePage = new APShoppingCartOrderSummaryBankwirePage(driver); apShoppingCartPaymentMethodPage = new APShoppingCartPaymentMethodPage(driver); apShoppingCartShippingPage = new APShoppingCartShippingPage(driver); apShoppingCartSummaryPage = new APShoppingCartSummaryPage(driver); baseURL = propertyReader.getProperty(propertiesFile, "AUTOMATION_PRACTICE_URL"); } @AfterTest(alwaysRun = true) public void tearDown() { Log.info("I am in After Method! Test is ending!"); driver.close(); driver.quit(); } }
И мои тесты следующие.-
public class AutomationPracticesTests extends BaseTest { // Properties private String emailAddress, password; // Tests @Test(description = "It creates a new user in the store", priority = 1) public void CreateNewUserWithValidData(Method method) { startTest(method.getName(), "It creates a new user in the store"); emailAddress = Mocks.personalData().get(0).getEmail(); password = Mocks.personalData().get(0).getPassword(); apHomePage.goTo(baseURL); apHomePage.clickOnSignInButton(); apAuthenticationPage.fillCreateAccountForm(emailAddress); apAuthenticationPage.clickOnCreateAccountButton(); apCreateAccountPage.fillRegisterForm(Mocks.personalData()); apCreateAccountPage.clickOnRegisterButton(); Assert.assertTrue(apMyAccountPage.isLoaded()); } @Test(description = "It logins successfully in the store with a valid user", priority = 2) public void LoginWithAValidUser(Method method) { apHomePage.goTo(baseURL); apHomePage.clickOnSignInButton(); apAuthenticationPage.fillSignInForm(emailAddress, password); apAuthenticationPage.clickOnSignInButton(); Assert.assertTrue(apMyAccountPage.isLoaded()); } @Test(description = "It throws an error when the user attempts to login with an invalid user", priority = 3) public void LoginWithAnInvalidUser(Method method) { apHomePage.goTo(baseURL); apHomePage.clickOnSignInButton(); apAuthenticationPage.fillSignInForm(Mocks.invalidPersonalData().getEmail(), Mocks.invalidPersonalData().getPassword()); apAuthenticationPage.clickOnSignInButton(); Assert.assertEquals("Authentication failed.", apAuthenticationPage.IsErrorBannerDisplayed()); } }
Я подозреваю, что это как-то связано с testng.xml файл (но, tbh, есть некоторые вещи, которые я не понимаю в том, как правильно настроить этот файл).
Я буду признателен за любую помощь в решении моей проблемы. Заранее спасибо!
Комментарии:
1. когда выполняются другие тесты, какие тесты выполняются ?? @AfterTest вызывается только после выполнения тестов в теге теста . В вашем testng.xml существует только один тег lt;testgt;
2. @nhatnq Выполняется первый тест
CreateNewUserWithValidData()
, и когда он заканчивается, он не вызываетAfterTest
метод. Честно говоря, как я уже упоминал в посте, я не понимаю, как правильно настроить XML-файл. Какой должна быть правильная структура для правильного выполнения тестов? Вы имеете в виду, что мне нужно триlt;testgt;
узла для каждого метода тестирования, который у меня есть в моемAutomationPracticeTests
классе?3. Да, вам нужно создать 3 тега lt;testgt;, чтобы они были установлены правильно
Ответ №1:
Это не ошибка. Все работает так, как и ожидалось.
BeforeTest BeforeMethod Method 1: CreateNewUserWithValidData BeforeMethod Method 2: LoginWithAValidUser BeforeMethod Method 3: LoginWithAnInvalidUser AfterTest
Если вы хотите закрыть браузер до метода 2, то вам нужно изменить AfterTest
— gt; gt; AfterMethod
и инициализировать браузер в BeforeMethod
Если вы просто хотите изменить testng.xml
lt;test name="test1"gt; lt;classesgt; lt;class name="Tests.AutomationPracticesTests"gt; lt;methodsgt; lt;include name="CreateNewUserWithValidData"/gt; lt;/methodsgt; lt;/classgt; lt;/classesgt; lt;/testgt; lt;test name="test2"gt; lt;classesgt; lt;class name="Tests.AutomationPracticesTests"gt; lt;methodsgt; lt;include name="LoginWithAValidUser"/gt; lt;/methodsgt; lt;/classgt; lt;/classesgt; lt;/testgt; lt;test name="test3"gt; lt;classesgt; lt;class name="Tests.AutomationPracticesTests"gt; lt;methodsgt; lt;include name="LoginWithAnInvalidUser"/gt; lt;/methodsgt; lt;/classgt; lt;/classesgt; lt;/testgt;
Комментарии:
1. Есть ли другой способ настроить
testng.xml
файл для использования@BeforeTest
@AfterTest
аннотаций и?2. @ArCiGo Я обновил свой ответ
3. Неплохо. Спасибо, чувак!