assertions selenium using junit
이 어설 션에 대한이 Selenium 자습서에서는 Junit 및 TestNG 프레임 워크를 사용하는 셀레늄의 어설 션 및 다양한 유형의 어설 션 및 어설 션 방법에 대해 설명합니다.
어설 션은 테스트 케이스의 유효성을 검사하는 데 사용되며 테스트 케이스가 통과했는지 실패했는지 이해하는 데 도움이됩니다. 응용 프로그램의 실제 결과가 예상 결과와 일치하면 어설 션이 충족 된 것으로 간주됩니다.
Selenium을 사용하여 웹 애플리케이션을 자동화하는 동안 테스트가 예상대로 작동하는지 확인하기 위해 테스트를 검증해야합니다.(즉, 테스트 케이스 결과가 합격 / 불합격 인 경우).
테스트 케이스는 모든 어설 션이 충족 된 경우에만 통과 된 것으로 간주됩니다. Selenium의 어설 션은 Junit 및 TestNG 프레임 워크의 사전 정의 된 방법으로 처리 할 수 있습니다. 이에 대해서는이 기사에서 자세히 설명합니다.
학습 내용 :
셀레늄의 주장
어설 션은 테스트 케이스에서 다양한 종류의 유효성 검사를 수행하는 데 사용되며 테스트 케이스가 통과했는지 실패했는지를 결정하는 데 도움이됩니다. We 테스트가 예외없이 실행되면 성공한 것으로 간주합니다.
어설 션에 대한 비디오 자습서
셀레늄의 어설 션 유형
Selenium에는 두 가지 유형의 어설 션이 있으며 범주화는 조건이 통과 또는 실패한 후 어설 션이 어떻게 작동하는지에 따라 다릅니다.
여기서 우리는 두 가지 유형의 주장을 셀렌 :
- 어려운 주장
- 소프트 어설 션
샘플을 보려면 여기를 클릭하십시오. 테스트 케이스 어설 션 테스트 용.
# 1) 하드 어설 션 (또는 단순히 어설 션)
하드 어설 션은 어설 션 조건이 충족 될 때까지 실행을 계속하지 않습니다.
하드 어설 션은 일반적으로 어설 션 조건이 충족되지 않을 때마다 어설 션 오류를 발생시킵니다. 하드 어설 션 조건이 실패하면 테스트 케이스가 즉시 실패로 표시됩니다.
이러한 종류의 어설 션을 사용하는 시나리오는 올바르게 로그인했는지 확인하고 성공적으로 로그인하지 않은 경우 테스트에 실패하고 싶을 때 전제 조건 ( 로그인) 자체가 실패합니다.
여기에 설명 된 또 다른 예를 살펴 보겠습니다.
웹 페이지의 제목을 주장하는 테스트 사례를 고려하십시오.
public class LearnAssertions { WebDriver driver; //Store current project workspace location in a string variable ‘path’ String path = System.getProperty('user.dir”); @BeforeTest public void SetDriver(){ //Mention the location of ChromeDriver in localsystem System.setProperty('webdriver.chrome.driver',path+'\Drivers\chromedriver.exe'); driver = new ChromeDriver();// Object is created- Chrome browser is opened driver.manage().window().maximize(); } @Test public void verifyTitle() { driver.get(https://www.amazon.com); String ActualTitle = driver.getTitle(); String ExpectedTitle = “Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more”; Assert.assertEquals(ActualTitle, ExpectedTitle); System.out.println(“Assert passed”); } @AfterTest public void closedriver(){ //closes the browser instance driver.close(); }
이 예에서‘ActualTitle’변수는 자동화의 제목 텍스트를 보유합니다. ‘ExpectedTitle’은 예상되는 문자열 데이터를 보유합니다. Assert.assertEquals ()는 두 텍스트가 동일한 지 확인합니다. 위의 테스트 케이스는 실제 텍스트와 예상 텍스트가 동일하므로 통과하고 다음 실행 행으로 계속됩니다.
콘솔 :
Assert가 통과되었습니다.
통과 : VerifyTitle
실패한 동일한 테스트 케이스는 예외를 발생시키고 해당 인스턴스에서 실행을 중지합니다.
이제 예상 제목을 잘못된 제목으로 변경하겠습니다.
public class LearnAssertions { WebDriver driver; //Store current project workspace location in a string variable ‘path’ String path = System.getProperty('user.dir'); @BeforeTest public void SetDriver(){ //Mention the location of chromeDriver in localsystem System.setProperty('webdriver.chrome.driver',path+'\Drivers\chromedriver.exe'); driver = new ChromeDriver();// Object is created- Chrome browser is opened driver.manage().window().maximize(); } @Test public void verifyTitle() { driver.get(https://www.amazon.com); String ActualTitle = driver.getTitle(); String ExpectedTitle = “Welcome to Amazon”; Assert.assertEquals(ActualTitle, ExpectedTitle); System.out.println(“Assert passed”); } @AfterTest public void closedriver(){ //closes the browser instance driver.close(); }
콘솔:
java.lang.AssertionError :예상 됨 (아마존에 오신 것을 환영합니다)그러나발견 (Amazon.com : 전자 제품, 의류, 컴퓨터, 서적, DVD 등을위한 온라인 쇼핑)
콘솔에서 Assert 문에서 오류가 발생하고 예외가 발생했기 때문에 print 문을 건너 뛰었 음을 알 수 있습니다 (System.out.println).
# 2) 소프트 어설 션
소프트 어설 션은 어설 션 조건이 충족되지 않더라도 테스트 실행의 다음 단계에서 계속됩니다.
소프트 어설 션은 요청하지 않는 한 어설 션이 실패 할 때 자동으로 예외를 발생시키지 않는 어설 션 유형입니다. 이는 한 양식에서 여러 유효성 검사를 수행하는 경우에 유용합니다.이 중 몇 가지 유효성 검사 만 테스트 케이스 상태를 결정하는 데 직접적인 영향을줍니다.
여기에서는 SoftAssert라는 클래스를 사용하고 assertAll () 메서드를 호출하여 실행 중에 포착 된 모든 예외를 throw합니다. softAssert를 사용하면 assertion을 수행하고 예외가 발견되면 즉시 throw되지 않고 catchAll () 메서드를 호출하여 모든 예외를 throw 할 때까지 계속됩니다.
각 테스트 케이스에 대해 'SoftAssert'클래스의 다른 개체를 사용하는 것이 좋습니다.
페이지 제목을 주장하는 테스트 사례를 고려하십시오.
아래 예에서는 두 개의 서로 다른 테스트 케이스에서 사용하기 위해 'SoftAssert'클래스의 두 개체가 생성됩니다.
public class LearnAssertionsSoft { WebDriver driver; //Object of Class SoftAssert is created to use its methods SoftAssert softassert = new SoftAssert(); SoftAssert softassert2 = new SoftAssert(); //current project workspace String path = System.getProperty('user.dir'); @BeforeTest public void SetDriver(){ System.setProperty('webdriver.chrome.driver',path+'\Drivers\chromedriver.exe'); driver = new ChromeDriver();// Object is created - Chrome browser is opened driver.manage().window().maximize(); } //Soft Assertion example - with a failure test case example @Test public void verifyTitle(){ driver.get('https://amazon.in'); String ActualTitle = driver.getTitle(); System.out.println('Actual Title :'+ActualTitle); String ExpectedTitle = 'cameras, books, watches, apparel, shoes and e-Gift Cards. Free Shipping & Cash on Delivery Available.'; //Soft assert applied to verify title softassert.assertEquals(ActualTitle, ExpectedTitle); //If failed, this line gets printed and execution is not halted System.out.println('Assertion 1 is executed”); softassert.assertAll(); } //Soft Assertion example - with a positive flow test case example @Test public void verifyElement(){ WebElement AmazonIcon = driver.findElement(By.Xpath(“//div(contains(@id,’amazon_icon’))); softassert2.assertEquals (true, AmazonIcon.isDisplayed()); softassert2.assertAll(); System.out.println('Icon is displayed'); System.out.println('Assertion 2 is executed”); } @AfterTest public void closedriver(){ driver.close(); //Checks for failures if any and throws them at the end of execution } }
콘솔:
실제 제목 : Amazon.com : 전자 제품, 의류, 컴퓨터, 책, DVD 등을위한 온라인 쇼핑
어설 션 1이 실행됩니다.
아이콘이 표시됩니다.
어설 션 2가 실행됩니다.
java.lang.AssertionError : 다음 어설 션이 실패했습니다.
예상 됨 (아마존에 오신 것을 환영합니다)하지만 발견됨 (Amazon.com : 전자 제품, 의류, 컴퓨터, 도서, DVD 등을위한 온라인 쇼핑)
콘솔을 통해 첫 번째 테스트 케이스 (verifyTitle)에서 어설 션이 실패 했음에도 불구하고 실행은 'Assertion 1 is execute'문이 인쇄 된 다음 행으로 계속되었고 softAssert가 호출 된 후에 만 실행되었음을 알 수 있습니다. 예외가 발생했습니다.
Hard and Soft Assertion은 언제 사용합니까?
어설 션이 실패한 후에도 실행될 테스트 케이스의 모든 단계를 실행해야하고 어설 션 예외도보고하려면 소프트 어설 션 사용을 선택하십시오. 테스트 스크립트에서 소프트 어설 션을 사용하는 것은 테스트 실행을 처리하는 좋은 방법이자 효과적인 방법입니다.
어설 션이 통과 된 후에 만 테스트 케이스 실행을 진행하려는 경우 ( 예를 들어, 유효한 로그인을 확인하고 다른 단계 만 실행하려면) 하드 어설 션을 사용하십시오.
Junit Assert 방법
다양한 유형의 Junit Assert 방법이 아래에 자세히 설명되어 있습니다.
# 1) assertEquals
assertequals 메서드는 예상 결과와 실제 결과를 비교합니다. 예상 결과가 실제 결과와 일치하지 않으면 AssertionError를 발생시키고 assert equals 메소드에서 프로그램 실행을 종료합니다.
통사론:
public static void assertEquals(String expected, String actual)
예:
예상되는 문자열 =“https://www.google.com”;
String actualURL =“https://www.google.com”;
Assert.assertEquals (expected, actualURL);
# 2) assertTrue
asserttrue 메서드는 지정된 조건이 참이라고 주장합니다.
즉, 하나는 메시지이고 다른 하나는 어설 션을 적용해야하는 조건입니다. asserttrue 메서드에 전달 된 조건이 충족되지 않으면 AssertionError가 발생합니다.
통사론:
public static void assertTrue(java.lang.String message, boolean condition)
message – 어설 션 오류가 발생한 경우 표시 할 메시지입니다.
condition – 어설 션을 적용해야하는 조건입니다.
예:
Assert.assertTrue ( 'Assert True 테스트 메시지', true);
# 3) assertFalse
assert false 메소드는 지정된 조건이 거짓임을 주장합니다.
즉, 하나는 메시지이고 다른 하나는 어설 션을 적용해야하는 조건입니다. assertfalse 메서드에 전달 된 조건이 충족되지 않으면 AssertionError가 발생합니다.
통사론:
public static void assertFalse(java.lang.String message, boolean condition)
message – 어설 션 오류가 발생한 경우 표시 할 메시지입니다.
condition – 어설 션을 적용해야하는 조건입니다.
예:
Assert.assertFalse (“Assert false test message”false);
# 4) assertNull
assert null은 제공된 개체에 null 값이 포함되어 있는지 확인하는 데 사용됩니다. 개체를 매개 변수로 사용하고 제공된 개체에 null 값이 없으면 AssertionError가 발생합니다.
통사론:
public static void assertNull(Object object)
예:
DemoClass 데모 = new DemoClass ();
Assert.assertNull (데모);
# 5) assertNotNull
assert not null은 제공된 개체가 null 값을 보유하지 않는지 확인하는 데 사용됩니다. 개체를 매개 변수로 사용하고 제공된 개체에 null 값이 포함되어 있지 않으면 AssertionError가 발생합니다.
통사론:
public static void assertNotNull(Object object)
예:
DemoClass 데모 = new DemoClass ();
Assert.assertNotNull (데모);
# 6) assertSame
assert same 메소드는 매개 변수로 제공된 두 객체가 동일한 객체를 참조하는지 확인합니다. 제공된 객체가 제공된 메시지와 동일한 객체를 참조하지 않으면 AssertionError가 발생합니다.
Assert same은 개체의 참조 만 비교하지만 실제 값은 비교하지 않습니다.
통사론:
public static void assertSame(String message, Object expected,Object actual)
예:
DemoClass1 demo1 = 새로운 DemoClass1 ();
DemoClass2 demo2 = new DemoClass2 ();
Assert.assertSame ( '두 개체가 같음', demo1, demo2);
# 7) assertNotSame
assert not same은 두 개체가 같지 않음을 확인합니다. 두 개체가 동일한 개체를 참조하는 경우 AssertionError가 발생합니다.
assert not same 메서드는 객체에있는 값이 아닌 객체의 참조를 비교합니다.
통사론:
public static void assertNotSame(String message, Object expected, Object actual)
예:
DemoClass1 demo1 = 새로운 DemoClass1 ();
DemoClass2 demo2 = new DemoClass2 ();
Assert.assertNotSame (“두 개체가 같지 않습니다”, demo1, demo2);
# 8) assertArrayEquals
assert equals는 두 개체 배열이 같은지 확인합니다. 두 배열이 모두 null 값을 보유하면 동일한 것으로 간주됩니다. 이 메서드는 두 개체 배열이 동일하지 않은 경우 제공된 메시지와 함께 AssertionError를 발생시킵니다.
통사론:
public static void assertArrayEquals(String message, Object() expected, Object() actual)
message – 어설 션 오류가 발생한 경우 표시 할 메시지입니다.
expected – 개체 배열입니다.
actual – 개체의 배열.
예:
String () expected = {“Mango”,”Apple”,”Banana”}
String () actual = {“Mango”,”Apple”,”Banana”}
Assert.assertArrayEquals (expected, actual);
TestNG Assert 방법
TestNG Assert 메서드는 위에서 설명한 Junit assertion 메서드와 동일합니다. 메이저 Junit과 TestNG의 차이점 어설 션 메서드는 어설 션을 처리하는 방식으로 제공됩니다.
TestNG는 종속 클래스, 그룹 테스트, 매개 변수화 된 테스트 등과 같은 고급 어설 션 처리 기술을 제공합니다.
TestNG Assert 메서드에 대한 비디오 자습서
파트 I
파트 II
파트 III
# 1) assertEquals
이 메서드는 두 데이터 값이 같은지 확인하는 데 사용됩니다. 문자열, 부울, 정수와 같은 다양한 데이터 유형의 값을 비교할 수 있습니다. 등. 예상 값과 실제 값이 같을 때마다 예외없이 어설 션이 통과됩니다. 그렇지 않은 경우 AssertionError가 발생합니다.
용법 : 이러한 종류의 어설 션은 웹 페이지에 표시되는 데이터가 예상과 같거나 지정된 요구 사항에 맞는 경우를 확인하는 데 사용됩니다.
통사론:
Assert.assertEquals(actual,expected)
매개 변수 :
흐름 – 자동화에서 기대하는 실제 가치.
예상 – 예상 값.
예: 이를 확인하기 위해 Amazon 홈페이지에 'Amazon.com : 전자 제품, 의류, 컴퓨터, 책, DVD 등을위한 온라인 쇼핑 '
@Test public void verifyTitle() { WebDriver driver = new FirefoxDriver(); driver.get(https://www.amazon.com); String ActualTitle = driver.getTitle(); String ExpectedTitle = “Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more”; Assert.assertEquals(ActualTitle, ExpectedTitle); System.out.println(“Assert passed”); }
콘솔 :
Assert가 통과되었습니다.
통과 : VerifyTitle
위의 예에서 두 개의 문자열이 동일한 값인지 확인했습니다. 마찬가지로 정수, 부울 등과 같은 다른 데이터 유형의 동일성을 확인할 수 있습니다.
# 2) assertNotEquals
assertNotEquals는 두 데이터 값이 같지 않은지 확인하는 데 사용됩니다. assertEquals Assertion의 기능과는 정반대입니다. 예상 값과 실제 값이 일치 할 때마다 어설 션이 예외와 함께 실패하고 테스트 케이스를 '실패'로 표시합니다.
용법 : 웹 페이지에서 각 데이터가 고유한지 확인하고자 할 때 사용합니다. 예를 들어 , 2 개의 전화 번호가 동일하지 않은 전화 번호부.
통사론:
Assert.assertNotEquals(actual,expected)
매개 변수 :
흐름 – 자동화에서 기대하는 실제 가치.
예상 – 예상 값.
예: 서로 다른 두 영역의 핀 코드가 고유하거나 동일하지 않은지 확인합니다.
@Test // test case to verify AssertNotEquals public void verifyAssertNotEquals{ WebDriver driver = new FirefoxDriver(); driver.get('http://chennaiiq.com/chennai/pincode-by-name.php'); WebElement Adambakkam = driver.findElement(By.xpath('//table(contains(@class,'TBox'))/tbody/tr(5)/td(3)')); WebElement Aminijikarai = driver.findElement(By.xpath('//table(contains(@class,'TBox'))/tbody/tr(15)/td(3)')); String Pincode1 = Adambakkam.getText(); String Pincode2 = Aminijikarai.getText(); System.out.println('Two Unique pincodes are : ' +Pincode1 +' && '+Pincode2); Assert.assertNotEquals(Pincode1, Pincode2); System.out.println(“Assert passed”); }
콘솔 :
두 개의 고유 한 암호 : 600012 && 600001
Assert가 통과되었습니다.
통과 : verifyAssertNotEqual
# 3) assertTrue
assertTrue는 주어진 부울 조건이 참인지 확인하는 데 사용됩니다. 이 어설 션은 지정된 조건이 통과하면 true를 반환하고 그렇지 않으면 어설 션 오류가 발생합니다.
통사론:
Assert.assertTrue(BooleanCondition);
매개 변수 :
BooleanCondition – 반환 유형이 True인지 확인하는 조건.
용법 :
예: 확인하려면 Amazon.in의 홈페이지에 SignIn 버튼이 있는지 확인하십시오 (버튼 표시에 대한 어설 션).
Assert.assertTrue(SignIn.isDisplayed());
여기에서 부울 조건이- SignIn.IsDisplayed () TRUE를 반환합니다.
예: 웹 페이지에 버튼이 있는지 확인합니다.
@Test // Test cases for AssertTrue public void verifyAssertTrue(){ WebDriver driver = new FirefoxDriver(); driver.get('https://www.amazon.in');// Open browser and pass URL in address bar WebElement Navigation = driver.findElement(By.xpath('//*(@id='nav-link-yourAccount')')); WebElement SignInButton = driver.findElement(By.xpath('//span(text()='Sign in')')); Actions move = new Actions(driver); move.moveToElement(Navigation).build().perform(); Boolean checkButtonPresence = SignInButton.isDisplayed(); Assert.assertTrue(checkButtonPresence); System.out.println('Button is displayed'); }
콘솔 :
버튼이 표시됩니다.
통과 : verifyAssertTrue
# 4) assertFalse
assertFalse는 주어진 부울 조건이 거짓인지 확인하는 데 사용됩니다. 즉, 주어진 부울 조건의 반환 유형은 False 여야합니다. 이 어설 션은 지정된 조건에 FALSE 반환 유형이 있으면 통과합니다. 그렇지 않으면 어설 션 오류가 발생합니다.
통사론:
Assert.assertFlase(BooleanCondition);
매개 변수 :
BooleanCondition – 반환 유형이 False인지 확인하는 조건.
용법 : 사용할 수있는 시나리오는 특정 작업 후 웹 페이지에 요소가 없는지 확인하는 것입니다.
예 1 : 로그인 후 로그인 버튼이 표시되지 않아야합니다.
Assert.assertFalse(SignIn.isDisplayed());
이것은 부울 조건이- SignIn.IsDisplayed () FALSE를 반환합니다.
예 2 :
특정 작업 후 div가 사라지는 지 확인합니다. 따라서 여기에서 div가 표시되지 않았는지 확인합니다. 즉, 표시된 div의 잘못된 조건에 대해 Assert가 표시되는지 확인합니다.
@Test // Test case for AssertFalse public void verifyAssertFalse() throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get('https://www.irctc.co.in'); WebElement CaptchaDiv = driver.findElement(By.xpath('//div(contains(@id,'ImgContainer'))')); WebElement CheckBox = driver.findElement(By.xpath('//*(@id='otpId')')); CheckBox.click(); Assert.assertFalse(CaptchaDiv.isDisplayed()); System.out.println('Captcha div dimmed out of screen'); }
콘솔 :
Captcha div가 화면에서 흐리게 표시됨
통과 :verifyAssertFalse
# 5) assertNull
이 어설 션은 개체에 null 반환 값이 있는지 확인하는 데 사용됩니다. 즉, 결과가 null인지 확인합니다. 개체가 Null이면 예외없이 어설 션이 전달됩니다.
통사론:
AssertNull(Object)
매개 변수 :
목적 – 널값을 보유하는 모든 데이터 값.
용법:
예 1 :
문자열이 null인지 확인합니다.
@Test public void verifyAssertion () throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get('https://www.irctc.co.in'); String str1 = null; String str2 = 'hello'; AssertNull(str1); // asserts if str1 holds null value System.out.println('String holds null value – Assert passed'); }
예 2 :
크롬 드라이버를 시작하기 전에 드라이버 값이 null인지 확인합니다.
@Test public void verifyAssertion () throws InterruptedException { WebDriver driver; AssertNull(driver); System.out.println('Driver is null – Assert passed'); }
여기에서 드라이버 개체는 시작되지 않았으므로 null입니다. 따라서 AssertNull (드라이버)는 '드라이버'개체가 null 값을 보유하면 확인되므로 성공합니다.
# 6) assertNotNull
이 어설 션에는 Null 값이 아닌 유효한 반환 유형이 필요합니다. 즉, Null이 아닌 개체를 확인합니다. 반환 유형은 부울, 문자열, 정수, 목록 등일 수 있습니다. 객체가 null이 아닌 경우 Assertion이 전달되고 그렇지 않은 경우 AssertionError가 발생합니다.
통사론:
자바는 생성자를 사용하여 객체 배열을 만듭니다.
AssertNotNull(Object)
매개 변수 :
목적 – 데이터 값을 보유하는 모든 데이터 값.
용법:
예 1 : Assert는 일부 데이터를 보유하는 문자열입니다. 즉, Null이 아닙니다.
@Test public void verifyAssertion () throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get('https://www.irctc.co.in'); String str1 = null; String str2 = 'hello'; AssertNotNull(str2); // asserts if str2 holds some value System.out.println('String holds null value – Assert passed'); }
예 2 : FirefoxDriver를 시작한 후 드라이버 개체가 null이 아닌지 확인합니다.
@Test public void verifyAssertion () throws InterruptedException { WebDriver driver; WebDriver driver = new FirefoxDriver(); AssertNotNull(driver); System.out.println('Driver is null – Assert passed'); }
여기서 드라이버 개체는 파이어 폭스 드라이버로 시작되므로 '드라이버'개체는 시작되지 않았기 때문에 일부 값을 보유합니다. 따라서 AssertNotNull (드라이버)은 '드라이버'개체가 null 값을 보유하지 않는 경우 확인되므로 성공합니다.
딸깍 하는 소리 여기 샘플 테스트 케이스.
어설 션에 대한 샘플 프로그램
같음 주장 :
package Demo; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertionDemo { public static void main(String() args) throws InterruptedException{ String sValue = 'Assert Equals Test'; Assert.assertEquals('Assert Equals Test', sValue); System.out.println('Test Passed'); } }
코드 설명 :
위의 코드는 간단한 용어로 AssertEquals 메서드의 사용을 보여줍니다.
- 앞서 논의했듯이 assert equals는 예상 결과와 실제 결과라는 두 가지 매개 변수를받습니다. 예상 결과가 실제 결과와 일치하지 않으면 assertion 오류가 발생하고 assert equals 메서드에서 프로그램 실행이 종료됩니다.
- 위의 코드는 사용자 정의 문자열 값을 예상 문자열 값과 비교합니다.
- 실시간으로 실제 결과는 런타임에 값을 가져와 assert equals 메서드에 매개 변수로 전달하는 사용자 정의 작업입니다.
참으로 주장 :
package Demo; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertionsDemo1 { public static void main(String() args) throws InterruptedException{ String expectedTitle = 'Google'; System.setProperty('webdriver.gecko.driver','D:\Data_Personal\Demo\geckodriver-v0.23.0-win64\geckodriver.exe'); WebDriver driver = new FirefoxDriver(); driver.get('https://www.google.com'); Assert.assertTrue('Title does not match', expectedTitle.equals(driver.getTitle())); driver.close(); } }
코드 설명 :
위의 코드는 assertTrue 메서드의 사용법을 보여줍니다.
- 처음에는 예상되는 페이지 제목을 변수에 전달합니다. 그런 다음 firefox 드라이버의 개체를 인스턴스화하고 웹 페이지 (https://www.google.com)로 이동합니다.
- 나중에 assertsTrue 메소드를 사용하여 열린 페이지 제목과 예상 페이지 제목을 비교합니다. 열린 페이지 제목이 예상 된 제목과 일치하지 않으면 assertion 오류가 발생하고 assertTrue 메서드에서 프로그램 실행이 종료됩니다.
- 위의 코드는 실제 페이지 제목이 예상 페이지 제목과 일치 할 때만 성공적으로 실행됩니다.
거짓 주장 :
package Demo; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertionsDemo1 { public static void main(String() args) throws InterruptedException{ String expectedTitle = 'Google1'; System.setProperty('webdriver.gecko.driver','D:\Data_Personal\Demo\geckodriver-v0.23.0-win64\geckodriver.exe'); WebDriver driver = new FirefoxDriver(); driver.get('https://www.google.com'); Assert.assertFalse('Title does match', expectedTitle.equals(driver.getTitle())); driver.close(); } }
코드 설명 :
위의 코드는 assertfalse 메서드의 사용법을 보여줍니다.
- 처음에는 예상되는 페이지 제목을 변수에 전달한 다음 firefox 드라이버의 개체를 인스턴스화하고 웹 페이지 (https://www.google.com)로 이동합니다.
- 나중에 assertfalse 메서드를 사용하여 열린 페이지 제목을 예상 페이지 제목과 비교합니다. 열린 페이지 제목이 예상되는 제목과 일치하면 assertion 오류가 발생하고 assert false 메서드에서 프로그램 실행이 종료됩니다.
- 위 코드는 실제 페이지 제목이 예상되는 페이지 제목과 일치하지 않는 경우에만 성공적으로 실행됩니다.
어설 션에 대한 종단 간 코드
다음은 Assertions에 대한 샘플 종단 간 코드입니다. 단순화를 위해 다음 시나리오를 사용했습니다.
대본:
- Firefox 브라우저에서 웹 페이지 https://www.google.com을 엽니 다.
- asserttrue 메서드를 사용하여 열린 페이지 제목이 예상 페이지 제목과 동일한 지 확인합니다.
- 검색 텍스트 상자에 검색 키워드 Selenium을 입력하십시오.
- 키보드의 Enter 버튼을 누르십시오.
- assertequals 메소드 및 assertfalse 메소드를 사용하여 검색 결과 페이지에서 열린 페이지 제목이 예상 페이지 제목과 동일한 지 확인하십시오.
- 브라우저를 닫습니다.
샘플 코드 :
packageDemo; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertionsDemo { public static void main(String args()) throws InterruptedException { String expectedTitle = 'Google'; String expectedText = 'selenium - Google Search'; System.setProperty('webdriver.gecko.driver','D:\Data_Personal\Demo\geckodriver-v0.23.0-win64\geckodriver.exe'); // Open the web page https://www.google.com using firefox browser WebDriver driver = new FirefoxDriver(); driver.get('https://www.google.com'); // Validate if actual web page title matches with that of expected title using assert true method System.out.println('Assert true method validation'); Assert.assertTrue('Title does not match', expectedTitle.equals(driver.getTitle())); // Enter the keyword selenium on the search textbox WebElementsearchBox = driver.findElement(By.xpath('//*(@name='q')')); searchBox.sendKeys('selenium'); searchBox.sendKeys(Keys.ENTER); Thread.sleep(8000); // Validate the actual page title with expected page title using assert equals method System.out.println('Assert equals method validation'); Assert.assertEquals(expectedText, driver.getTitle()); // Page title validation using assert false method System.out.println('Assert false method validation'); Assert.assertFalse('Title does match', expectedTitle.equals(driver.getTitle())); // Close the current browser driver.close(); } }
코드 출력 :
처음에는 웹 페이지 https://www.google.com과 함께 Firefox 브라우저 창이 열립니다. Asserttrue 메서드는 열린 페이지 제목이 예상되는 페이지 제목 인 Google의 제목과 일치하는지 확인합니다.
스크립트는 검색 키워드를 Selenium으로 입력하고 Enter 버튼을 누릅니다.
Assertfalse 및 assertequals 메서드는 검색 결과 화면의 실제 페이지 제목이 예상 제목 인‘셀레늄 – Google 검색’의 제목과 일치하는지 비교합니다. 브라우저는 driver.close 메소드를 통해 닫힙니다.
콘솔 출력 :
아래 주어진 텍스트는 Eclipse IDE의 콘솔 출력입니다.
Assert 클래스를 사용하는 동안 일반적인 실수 방지
1. 프로젝트에 JUnit, TestNG 및 Python 라이브러리가 구성되어 있다고 가정합니다.
두 . 그러나 스크립트에서 TestNG 주석을 사용하고 있으며 실수로 Junit Assertion을 선택하면 Assert 클래스가 더 이상 사용되지 않습니다. 아래 스크린 샷 참조
삼. 따라서 TestNg는 유일한 조직을 선택하므로 적절한 Assert 클래스를 선택하는 것이 매우 중요합니다.
네. Junit의 경우 org.junit.Assert 클래스 등을 선택하십시오.
5. Soft Assertion을 수행하려면 assertAll () 메서드를 강제로 호출해야합니다.
6. 어설 션이 실패하면 예외가 아닌 어설 션 오류가 발생합니다.
결론
아래 포인터를 사용하여 Selenium의 Assertions에 대한이 기사를 마무리 할 수 있습니다.
- 어설 션은 응용 프로그램의 실제 결과와 예상 결과를 비교하는 데 사용됩니다.
- 테스트 케이스는 모든 어설 션이 충족 된 경우에만 통과 된 것으로 간주됩니다.
- AssertEquals 메서드는 예상 결과를 실제 결과와 비교합니다. 예상 결과가 실제 결과와 일치하지 않으면 AssertionError를 발생시키고 assertequals 메서드에서 프로그램 실행을 종료합니다.
- AssertTrue 메서드는 지정된 조건이 참이라고 주장합니다. asserttrue 메서드에 전달 된 조건이 충족되지 않으면 AssertionError가 발생합니다.
- AssertFalse 메서드는 지정된 조건이 거짓임을 주장합니다. assert false 메서드에 전달 된 조건이 충족되지 않으면 AssertionError가 발생합니다.
- AssertEquals, AssertTrue 및 AssertFalse 메서드는 Selenium에서 가장 일반적으로 사용되는 어설 션입니다.
에서 예정된 튜토리얼 , 우리는 실시간 프로젝트 시나리오에서 사용되는 다양한 예를 논의하고 목적에 따라 어설 션이 어떻게 사용되는지 이해합니다.
이 기사가 Selenium의 Assertions에 대한 지식을 풍부하게 해주기를 바랍니다 !!
=> Easy Selenium 교육 시리즈를 읽어보십시오.
추천 도서
- JUnit 프레임 워크 소개 및 Selenium 스크립트에서의 사용법 – Selenium Tutorial # 11
- TestNG 프레임 워크를 사용하여 Selenium 스크립트를 작성하는 방법-TestNG Selenium Tutorial # 12
- Selenium에서 TestNG 주석을 사용하는 방법 알아보기 (예제 포함)
- Cucumber Selenium 튜토리얼 : Cucumber Java Selenium WebDriver 통합
- Selenium과 JMeter의 통합
- Selenium WebDriver 소개 – Selenium Tutorial # 8
- 각각의 장단점이있는 가장 인기있는 테스트 자동화 프레임 워크 – Selenium Tutorial # 20
- 30 개 이상의 최고의 셀레늄 튜토리얼 : 실제 예제로 셀레늄 배우기