简体   繁体   English

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

[英]Assert try/catch block not working as intended

When I run my Selenium script, the assertion method I use sorta works. 当我运行Selenium脚本时,我使用sorta的断言方法有效。 When the assertion is met (element is present), the script writes to an xls file. 满足断言时(存在元素),脚本将写入xls文件。 When it is not met, the script does not write to the xls file, and it it stops the test right there. 如果不符合要求,则脚本不会写入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"
                });
            }

Here are my excel writer methods: 这是我的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"
        });

    }

And: 和:

@AfterClass
    public void setupAfterSuite(ITestContext context) {
        //write excel file and file name is TestResult.xls 
        Set < String > keyset = testresultdata.keySet();
        int rownum = 0;
        for (String key: keyset) {
            Row row = sheet.createRow(rownum++);
            Object[] objArr = testresultdata.get(key);
            int cellnum = 0;
            for (Object obj: objArr) {
                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);
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(new File("C:/Users/matt_damon/workspace/project/passfail.xls"));
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

So why, even when I purposely make my test fail, does the excel writer not write the fail entry? 那么,为什么即使我故意使测试失败,excel编写器也不会编写失败条目?

Check what aseertEquals() actually does. 检查aseertEquals()实际执行的操作。 Most probably it throws java.lang.AssertionError , which is not subclass of java.lang.Exception . 它很可能抛出java.lang.AssertionError ,它不是 java.lang.Exception子类。

That's at least what JUnit's Assert.assert*() methods do. 至少这就是JUnit的Assert.assert*()方法所做的。

In test frameworks there are listeners you use to include actions after an assert. 在测试框架中,您可以使用侦听器在断言之后包括动作。

Depending on which test framework you use, there are different implementations. 根据您使用的测试框架,有不同的实现。 But I assume you use JUnit. 但我假设您使用JUnit。 (If you can change to TestNG, much easier and better) (如果可以更改为TestNG,则变得更加容易和更好)

Credit this to MEMORYNOTFOUND at JUnit Listener 将此归功于JUnit Listener的 MEMORYNOTFOUND

JUnit Listener JUnit侦听器

These are the options for where the listener can intercept test reesults. 这些是侦听器可以拦截测试结果的选项。 These include a lot of information such as name of the test case. 这些包括很多信息,例如测试用例的名称。 Since you want to pass information, you have to add it to the message and in the listener parse the information you need. 由于要传递信息,因此必须将其添加到消息中,并在侦听器中解析所需的信息。

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());
  }
}

JUnit Runner The listener has to be added to the test execution. JUnit Runner必须将侦听器添加到测试执行中。

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 Test case JUnit测试用例

All test classes which include the annotation @RunWith activates the listener 所有包含注解@RunWith的测试类都会激活侦听器

package com.memorynotfound.test;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertTrue;

@RunWith(MyRunner.class)
public class RunListenerTest {

    @Test
    public void testListener(){

    }

    @Test
    public void testFalseAssertion(){
        assertTrue("3d, User should not be able to login with no password, Login failed, Fail",false);
    }

    @Ignore
    @Test
    public void testIgnore(){

    }

    @Test
    public void testException(){
        throw new RuntimeException();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM