由于在单元测试中模拟数据库映射器,因此无法实例化DataAccess类

时间:2019-01-07 15:51:42

标签: java unit-testing mockito jmockit

在尝试测试我的数据访问类时遇到错误:

  

原因:org.apache.ibatis.builder.BuilderException:解析SQL Mapper配置时出错。原因:org.apache.ibatis.datasource.DataSourceException

测试类:

@Tested
DataAccess dataAccess;

@Mock
Mapper mapper;

DataAccess类:

private Logger logger;

private final Mapper mapper;

public DataAccess() {
    String loggerCategory = new properties().getLoggerCategory();
    logger = LoggerFactory.getLogger(loggerCategory);

    mapper = DBControl.getAutoClosingMapper(
            Mapper.class, DataSource.source, logger);
}

DBControl(错误来自哪里):

private static final SqlSessionFactory sqlMapper;

static {
   Reader reader = null;
   String resource = "configuration.database.xml";
   reader = Resources.getResourceAsReader(resource);

   //the exception is getting thrown from this line
   sqlMapper = new SqlSessionFactoryBuilder().build(reader);
}

我在测试类中尝试了几种不同的Mockito和jmockit批注,但每次都会遇到相同的错误。

我只需要模拟映射器。

1 个答案:

答案 0 :(得分:1)

我在这里注意到的一件事是,您正在使用@Mock批注尝试模拟最终的类变量,除非您在某个地方有构造函数,否则通常不会起作用。

例如

public class DataAccess{

   private final Mapper mapper;
   DataAccess(mapper){
    this.mapper = mapper
    // anything else
   }
}

使用Mockito,您可以执行以下操作:

public class TestClass{
 private DataAccess dataAccess = new DataAccess(Mockito.mock(Mapper.class));
}

此外,我通常会在声明Logger时实例化它;

private final Logger LOGGER = LoggerFactory.getLogger(getClass());