【问题标题】:Cannot instantiate class DataAccess because of mocking DB mapper in unit test由于在单元测试中模拟 DB 映射器,无法实例化类 DataAccess
【发布时间】:2019-01-07 15:51:41
【问题描述】:

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

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

测试类:

@Tested
DataAccess dataAccess;

@Mock
Mapper mapper;

数据访问类:

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

我只需要模拟映射器。

【问题讨论】:

  • 我认为问题在于 DBControl 中使用的静态块。我不确定这可以被嘲笑。也许您可以在测试模块中添加所需的 xml-File。
  • 你能发布一些测试代码吗?你只发布了两个类变量。
  • @PhilNinan 测试类在初始化DataAccess 时抛出错误。它甚至没有参加考试。无论我尝试运行什么测试,错误都是相同的。

标签: java unit-testing mockito jmockit


【解决方案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());

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多