<noscript><img alt="Assert condition failed" class="alignnone size-full wp-image-14150" height="340" src="img/9272cef7d4d831fd5ed1b3ae54bbd374.png" width="720"/><p>上图中的控制台显示<code>assertEquals</code>条件成功,因此将打印检查后的语句,“<strong>声明等于通过。 </strong>”,而<code>assertNotEquals</code>条件失败,因此将不执行此检查之后的行。 打印语句“<strong>声明不等于失败</strong>”不会打印到控制台。</p><h3>情况 3:尽管 assertNotEquals 条件失败,但通过测试用例</h3><p>要仅验证实际值和预期值是否不相等,请使用<code>try-catch</code>块。</p><p><strong>Code snippet</strong></p><pre><code class="language-java">//Verify title not equal using try-catch block try { // Making the test fail Assert.assertNotEquals("WebDriver Demo Website", pageTitle); } catch(Error e){ // Following lines will be printed when the assert condition fails System.out.println("Assert not equals failed. But test execution is not aborted."); System.out.println("Error message: " + e.toString()); }</code></pre><p>即使<code>assertNotEquals</code>条件失败,catch 块中的语句也将被执行,并且错误消息将被打印到控制台。</p><p><img alt="Verify condition fails" class="alignnone size-full wp-image-14149" data-lazy-sizes="(max-width: 825px) 100vw, 825px" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg" data-lazy-srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg 825w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-300x124.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-768x318.jpg 768w" height="342" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20825%20342'%3E%3C/svg%3E" width="825"/></p><noscript><img alt="Verify condition fails" class="alignnone size-full wp-image-14149" height="342" sizes="(max-width: 825px) 100vw, 825px" src="img/d09793dee60556d778b6b7f310560194.png" srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg 825w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-300x124.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-768x318.jpg 768w" width="825"/><p>如图所示,测试用例执行成功,并且错误被打印到控制台。</p><h2>完整的代码</h2><pre><code class="language-java">import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertAndVerify { // Declaring variables private WebDriver driver; private String baseUrl; @Before public void setUp() throws Exception { // Selenium version 3 beta releases require system property set up System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\" + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe"); // Create a new instance for the class FirefoxDriver // that implements WebDriver interface driver = new FirefoxDriver(); // Implicit wait for 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Assign the URL to be invoked to a String variable baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/"; } @Test public void testPageTitle() throws Exception { // Open baseUrl in Firefox browser window driver.get(baseUrl); // Get the page title String pageTitle = driver.getTitle(); // Print the title to console System.out.println("The actual title is: " + pageTitle); // Check if actual and expected values are equal Assert.assertEquals("WebDriver Demo Website", pageTitle); // Printing success message System.out.println("Assert equals passed."); // Making the test fail //Assert.assertNotEquals("WebDriver Demo Website", pageTitle); // Following lines will not be executed as above assert condition fails //System.out.println("Assert not equals failed"); //Verify title not equal using try-catch block try { // Making the test fail Assert.assertNotEquals("WebDriver Demo Website", pageTitle); } catch(Error e){ // Following lines will be printed when the assert condition fails System.out.println("Assert not equals failed. But test execution is not aborted."); System.out.println("Error message: " + e.toString()); } } // End of @Test @After public void tearDown() throws Exception { // Close the Firefox browser driver.close(); } }</code></pre><p>所有代码文件都放置在<a href="https://github.com/JBTAdmin/Selenium/tree/master/WebDriver"> GitHub 存储库</a>中,以方便访问。 您可以为存储库加注星标和分支以方便使用。 请仔细阅读“README.md”文件以获取明确说明。</p><p>总结了断言和验证的这一部分。 祝你有美好的一天!</p><div class="sticky-nav" style="font-size: 15px;"><div class="sticky-nav-image"></div><div class="sticky-nav-holder"><div class="sticky-nav_item"><h6 class="heading-sm">下一篇文章</h6></div><h5 class="sticky-nav_heading " style="font-size: 15px;"><a href="https://javabeginnerstutorial.com/selenium/9s-webdriver-handling-text-boxes-images/" title="9s. WebDriver – Handling text boxes and images"> 9 秒。 WebDriver – 处理文本框和图像</a></h5></div></div> </body> </html></noscript>
<noscript><imgalt="POI download link"class="alignnone size-full wp-image-13586"height="433"sizes="(max-width: 859px) 100vw, 859px"src="img/66dde6eb58d06604bfe3993478f8010c.png"srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink.jpg 859w, https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink-300x151.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink-768x387.jpg 768w"width="859"/><h2><strong>步骤 2:</strong></h2><p>将这些 JAR 添加到我们的项目构建路径中。 确保选择“poi-x.xx”,“ooxml-lib”和“lib”文件夹下的所有 JAR。 我还将这些以及其他所有代码文件都放在了我们的<ahref="https://github.com/JBTAdmin/Selenium/tree/master/AdvancedWebDriver/Reading%20data%20from%20excel"> GitHub 存储库</a>中。</p><p>我们之前已经多次看到这种添加 JAR 来构建路径过程的内容,因此我没有在重复它(有关详细说明,请参阅此<ahref="https://javabeginnerstutorial.com/selenium/9b-webdriver-eclipse-setup/">文章</a>的步骤 3)。</p><h2><strong>步骤 3:</strong></h2><p>创建一个新类“<strong> ExcelOperationsUsingPOI.java </strong>”。 在此类中,让我们有一种从特定位置读取 excel 文件的特定图纸的方法。</p><li>通过传递您要打开的 excel 文件的完整文件路径来创建 File 类的对象-<codedata-enlighter-language="java">File file = new File(filePath+"\\"+fileName); </code></li><li>下一步是创建一个<em> FileInputStream </em>对象,以获取 excel 文件的输入字节-<codedata-enlighter-language="java">FileInputStream inputStream = new FileInputStream(file); </code></li><li>创建一个工作簿对象-<codedata-enlighter-language="java">Workbook myWorkbook = null; </code></li><li>Excel 文件在大多数情况下可以具有两个扩展名。 “.xls”或“.xlsx”。 通过使用子字符串方法拆分文件名来找到扩展名,并相应地创建 Workbook 对象。</li><pre><codeclass="language-java">//indexOf gives the index of . in the file name //substring method splits the string starting from index of . to the end String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class myWorkbook = new XSSFWorkbook(inputStream); } //Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of HSSFWorkbook class myWorkbook = new HSSFWorkbook(inputStream); }</code></pre><li>使用传递的确切工作表名称,可以读取特定工作表-<codedata-enlighter-language="java">Sheet mySheet = myWorkbook.getSheet(sheetName); </code></li><p>现在,使用行和列很容易,它们的交点将为我们提供我们希望读取的单元格内容。</p><p>现在让我们来看一下实现到目前为止讨论的全部功能的代码,</p><h3><strong> ExcelOperationsUsingPOI.java </strong></h3><pre><codeclass="language-java">import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelOperationsUsingPOI { public static void readExcel(String filePath,String fileName,String sheetName) throws IOException{ //Create a object of File class to open xlsx file File file = new File(filePath+"\\"+fileName); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); Workbook myWorkbook = null; //Find the file extension by spliting file name in substring and getting only extension name //indexOf gives the index of . in the file name //substring method splits the string starting from index of . to the end String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class myWorkbook = new XSSFWorkbook(inputStream); } //Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of HSSFWorkbook class myWorkbook = new HSSFWorkbook(inputStream); } //Read sheet inside the workbook by its name Sheet mySheet = myWorkbook.getSheet(sheetName); //Find number of rows in excel file int rowCount = mySheet.getLastRowNum()- mySheet.getFirstRowNum(); //Create a loop over all the rows of excel file to read it for (int i = 0; i < rowCount+1; i++) { Row row = mySheet.getRow(i); //Create a loop to print cell values in a row for (int j = 0; j < row.getLastCellNum(); j++) { //Print excel data in console System.out.print(row.getCell(j).getStringCellValue()+"|| "); } System.out.println(); } } }</code></pre><h3><strong> ReadExcelData.java </strong></h3><p>用于调用 readExcel 方法并传递必需的参数。</p><pre><codeclass="language-java">import java.io.IOException; import com.blog.utility.ExcelOperationsUsingPOI; public class ReadExcelData { public static void main(String[] args) { try { ExcelOperationsUsingPOI.readExcel("E:\\Selenium", "ReadUsingPOI.xlsx", "Demographics"); } catch (IOException e) { e.printStackTrace(); } } }</code></pre><p><spanclass="ezoic-adpicker-ad"id="ezoic-pub-ad-placeholder-124"></span><spanclass="ezoic-ad box-4 adtester-container adtester-container-124"data-ez-name="javabeginnerstutorial_com-box-4"style="display:block !important;float:none;margin-bottom:2px !important;margin-left:0px !important;margin-right:0px !important;margin-top:2px !important;min-height:110px;min-width:728px;text-align:center !important;"><spanclass="ezoic-ad ezoic-adl"ezah="90"ezaw="728"id="div-gpt-ad-javabeginnerstutorial_com-box-4-0"style="position:relative;z-index:0;display:inline-block;min-height:90px;min-width:728px;"></span></span>注释使代码不言自明。 所考虑的 Excel 工作表中的数据如下所示,</p><p><imgalt="Excel Sheet"class="alignnone size-full wp-image-13588"data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/3_ExcelSheet.jpg"height="287"src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20357%20287'%3E%3C/svg%3E"width="357"/></p><noscript><imgalt="Excel Sheet"class="alignnone size-full wp-image-13588"height="287"src="img/86b09846221b07ad4f56bd5bde566b64.png"width="357"/><p>使用我们的代码访问此信息将按预期方式打印出所有用管道分隔的值,以便将其控制台。</p><p><imgalt="excel console output"class="alignnone size-full wp-image-13587"data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/2_ConsoleOutput.jpg"height="177"src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20450%20177'%3E%3C/svg%3E"width="450"/></p><noscript><imgalt="excel console output"class="alignnone size-full wp-image-13587"height="177"src="img/afeb40dbbf98d4b1f60208d231d21f9c.png"width="450"/><p>如果您想检索代码段,请在注释部分大声疾呼,</p><ol><li>给定条目的从零开始的行和列索引</li><li>使用给定的从零开始的行和列索引的值</li><li>基于给定条目的列表中的所有行值</li><li>基于给定条目的列表中的所有列值</li></ol><p>试用这些功能,让我知道您是否遇到颠簸。</p><p>祝你今天愉快!</p><divclass="sticky-nav"style="font-size: 15px;"><divclass="sticky-nav-image"></div><divclass="sticky-nav-holder"><divclass="sticky-nav_item"><h6class="heading-sm">下一篇文章</h6></div><h5class="sticky-nav_heading "style="font-size: 15px;"><ahref="https://javabeginnerstutorial.com/selenium/10k-advanced-webdriver-using-log4j-part-1/"title="10k. Advanced WebDriver – Using Log4j Part 1"> 10k。 高级 WebDriver – 使用 Log4j 第 1 部分</a></h5></div></div></body></html></noscript>