由于在单元测试中模拟 DB 映射器,无法实例化 class DataAccess

Cannot instantiate class DataAccess because of mocking DB mapper in unit test

尝试测试我的数据访问时出现错误 class:

Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.datasource.DataSourceException

测试class:

@Tested
DataAccess dataAccess;

@Mock
Mapper mapper;

数据访问class:

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 注释 class 但每次都出现相同的错误。

我只需要模拟映射器。

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

例如

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