简体   繁体   English

测试类夹具内部的异常处理?

[英]Exception handling inside fixture of test class?

The line within <s></s> causes a ClassNotFoundException to be thrown and must be handled in order to compile. <s> </ s>中的行导致抛出ClassNotFoundException ,必须对其进行处理才能进行编译。 If I resolve the compile error by surrounding with try-catch then each unit test will be working with an uninitialized instance if the exception was thrown. 如果通过围绕try-catch解决了编译错误,那么如果引发了异常,则每个单元测试都将使用未初始化的实例进行工作。 What would happen if I add throws to the method signature? 如果在方法签名中添加throws ,将会发生什么?

@Test
public class PanelControllerTest {

    private PanelController panelController;

    @BeforeTest
    public void beforeTest() {

        panelController = <s>new PanelController();</s>

    }
}

I'm new to test fixtures and I'm assuming this would be a correct way to test an instance of the class. 我是测试夹具的新手,我假设这是测试类实例的正确方法。 What's the best way to handle exceptions inside the test fixture setup code? 处理测试装置设置代码中的异常的最佳方法是什么?

UPDATE: This seems to be the source of the exception called from PanelController: 更新:这似乎是从PanelController调用的异常的来源:

class DBAccess {
    public DBAccess(DBConnection dbConnection) throws ClassNotFoundException {
         Class.forName(Constants.jdbcDriver);
         ...
    }
}

The correct behavior is to capture the exception and fail the test run. 正确的行为是捕获异常并使测试运行失败。

@BeforeTest
public void beforeTest() {
  try{
    panelController = new PanelController();
  } catch (Exception e) {
    fail("Test failed because dependency could not be instantiated. Exception was:"+e.getMessage());
  }
}

In an ideal world you probably wouldn't be dependent on a db (because it's hard to manage their state for testing) when running tests, but use a mock object instead. 在理想的情况下,运行测试时,您可能不会依赖于db(因为很难管理其状态以进行测试),而应使用模拟对象。 Still, if you have to rely on it best to fail the test run if the db is out of order, and surface that as a direct failure. 不过,如果您必须最好地依靠它,则在数据库故障时无法通过测试运行,并将其视为直接故障。

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

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