Java 断言try/catch块未按预期工作

Java 断言try/catch块未按预期工作,java,excel,selenium,try-catch,Java,Excel,Selenium,Try Catch,当我运行Selenium脚本时,我使用的断言方法sorta起作用。当满足断言(元素存在)时,脚本将写入xls文件。当不满足该条件时,脚本不会写入xls文件,并立即停止测试 try { assertEquals(driver.findElement(By.xpath(prop.getProperty("failedlogin"))).getText(), "LOG IN"); //add pass entry to the excel

当我运行Selenium脚本时,我使用的断言方法sorta起作用。当满足断言(元素存在)时,脚本将写入xls文件。当不满足该条件时,脚本不会写入xls文件,并立即停止测试

try {
                assertEquals(driver.findElement(By.xpath(prop.getProperty("failedlogin"))).getText(), "LOG IN");
                //add pass entry to the excel sheet
                testresultdata.put("4", new Object[] {
                    3d, "User should not be able to login with no password", "Login failed", "Pass"
                });
            } catch (Exception e) {
                //add fail entry to the excel sheet
                testresultdata.put("4", new Object[] {
                    3d, "User should not be able to login with no password", "Login failed", "Fail"
                });
            }
以下是我的excel writer方法:

@BeforeClass(alwaysRun = true)
    public void setupBeforeSuite(ITestContext context) throws IOException {
        //create a new work book
        workbook = new HSSFWorkbook();
        //create a new work sheet
        sheet = workbook.createSheet("Test Result");
        testresultdata = new LinkedHashMap < String, Object[] > ();
        //add test result excel file column header
        //write the header in the first row
        testresultdata.put("1", new Object[] {
            "Test Step Id", "Action", "Expected Result", "Actual Result"
        });

    }
@BeforeClass(alwaysRun=true)
公共void setupBeforeSuite(ITestContext上下文)引发IOException{
//创建新的工作手册
工作簿=新的HSSF工作簿();
//创建新工作表
sheet=workbook.createSheet(“测试结果”);
testresultdata=newlinkedhashmap();
//添加测试结果excel文件列标题
//将标题写入第一行
testresultdata.put(“1”,新对象[]{
“测试步骤Id”、“操作”、“预期结果”、“实际结果”
});
}
以及:

@AfterClass
公共void setupAfterSuite(ITestContext上下文){
//编写excel文件,文件名为TestResult.xls
Setkeyset=testresultdata.keyset();
int rownum=0;
用于(字符串键:键集){
Row-Row=sheet.createRow(rownum++);
Object[]objArr=testresultdata.get(key);
int-cellnum=0;
用于(对象对象对象:对象对象对象){
Cell Cell=row.createCell(cellnum++);
if(obj instanceof Date)cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)cell.setCellValue((Boolean)obj);
else if(obj instanceof String)cell.setCellValue((String)obj);
else if(obj instanceof Double)cell.setCellValue((Double)obj);
}
}
试一试{
FileOutputStream out=新的FileOutputStream(新文件(“C:/Users/matt_damon/workspace/project/passfail.xls”);
练习册。写(出);
out.close();
System.out.println(“Excel编写成功…”);
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}

那么,为什么即使我故意让我的测试失败,excel编写器也不写失败条目呢?

检查
aseertEquals()
实际上做了什么。很可能它抛出了
java.lang.AssertionError
,它不是
java.lang.Exception
的子类


这至少是JUnit的
Assert.Assert*()
方法所做的。

检查
aseertEquals()
实际上做了什么。很可能它抛出了
java.lang.AssertionError
,它不是
java.lang.Exception
的子类


这至少是JUnit的Assert.Assert*()方法所做的。

在测试框架中,您可以使用侦听器在Assert之后包含操作

根据您使用的测试框架的不同,有不同的实现。但我假设您使用JUnit。(如果您可以更改为TestNG,则更容易、更好)

将此归功于MEMORYNOTFOUND at

JUnit侦听器

这些是侦听器可以截获测试结果的选项。这些选项包括很多信息,例如测试用例的名称。由于要传递信息,必须将其添加到消息中,并在侦听器中解析所需的信息

package com.memorynotfound.test;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class JUnitExecutionListener extends RunListener {

  public void testRunStarted(Description description) throws Exception {
      System.out.println("Number of tests to execute: " + description.testCount());
  }

  public void testRunFinished(Result result) throws Exception {
      System.out.println("Number of tests executed: " + result.getRunCount());
  }

  public void testStarted(Description description) throws Exception {
      System.out.println("Starting: " + description.getMethodName());
  }

  public void testFinished(Description description) throws Exception {
      System.out.println("Finished: " + description.getMethodName());
  }
  //This function will print your message added to the assert
  public void testFailure(Failure failure) throws Exception {
      System.out.println("Failed: " + failure.getMessage());
  }

  public void testAssumptionFailure(Failure failure) {
      System.out.println("Failed: " +  failure.getDescription().getMethodName());
  }

  public void testIgnored(Description description) throws Exception {
      System.out.println("Ignored: " + description.getMethodName());
  }
}
少年赛跑运动员 监听器必须添加到测试执行中

package com.memorynotfound.test;

import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

public class MyRunner extends BlockJUnit4ClassRunner {

    public MyRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override public void run(RunNotifier notifier){
        notifier.addListener(new JUnitExecutionListener());
        super.run(notifier);
    }
}

在测试框架中,您可以使用侦听器在断言之后包含操作

根据您使用的测试框架的不同,有不同的实现。但我假设您使用JUnit。(如果您可以更改为TestNG,则更容易、更好)

将此归功于MEMORYNOTFOUND at

JUnit侦听器

这些是侦听器可以截获测试结果的选项。这些选项包括很多信息,例如测试用例的名称。由于要传递信息,必须将其添加到消息中,并在侦听器中解析所需的信息

package com.memorynotfound.test;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class JUnitExecutionListener extends RunListener {

  public void testRunStarted(Description description) throws Exception {
      System.out.println("Number of tests to execute: " + description.testCount());
  }

  public void testRunFinished(Result result) throws Exception {
      System.out.println("Number of tests executed: " + result.getRunCount());
  }

  public void testStarted(Description description) throws Exception {
      System.out.println("Starting: " + description.getMethodName());
  }

  public void testFinished(Description description) throws Exception {
      System.out.println("Finished: " + description.getMethodName());
  }
  //This function will print your message added to the assert
  public void testFailure(Failure failure) throws Exception {
      System.out.println("Failed: " + failure.getMessage());
  }

  public void testAssumptionFailure(Failure failure) {
      System.out.println("Failed: " +  failure.getDescription().getMethodName());
  }

  public void testIgnored(Description description) throws Exception {
      System.out.println("Ignored: " + description.getMethodName());
  }
}
少年赛跑运动员 监听器必须添加到测试执行中

package com.memorynotfound.test;

import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

public class MyRunner extends BlockJUnit4ClassRunner {

    public MyRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override public void run(RunNotifier notifier){
        notifier.addListener(new JUnitExecutionListener());
        super.run(notifier);
    }
}

在这种情况下,我必须捕获断言错误,对吗?我的理解是,try/catch有点像if/else,只有catch更适合于异常,而不是什么。如果我错了,请纠正我。这会管用的,是的。但将其用作if/else不是一个好主意!它适合于执行需要的异常情况被中止并采取纠正措施。此外,抛出和捕获异常的速度比if/else慢100倍。在您的示例中,我肯定会使用if/else。在这种情况下,我必须捕获断言错误,对吗?我的理解是try/catch有点像if/else,只是捕获更容易ards异常和其他异常。如果我错了,请纠正我。这会管用的,是的。但将其用作if/else不是一个好主意!它适用于需要中止执行并采取纠正措施的异常情况。此外,与if/else相比,抛出和捕获异常的速度非常慢-想想慢100倍。在你身上例如,我肯定会使用if/else。