首页 > 解决方案 > 仅使用 Mockito 模拟新对象

问题描述

我在一个类中有这样的方法代码

public List<Auth_token> getAuthToken(String User) throws SQLException {
        List<Auth_token> usersList = new ArrayList<Auth_token>();
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rset = null;
        try {

            OracleDataSource dataSource = new OracleDataSource();
            dataSource.setURL("blah blah");
            dataSource.setUser("blah");

            //LOGGER.log(Level.INFO,"username +: "+config.getUsername());
            dataSource.setPassword("blah");

            Connection conn = dataSource.getConnection();
            String query = "blah query";
//more code
}

我只需要使用 mockito 来模拟 oracle 数据源。我知道如何使用 power mockito,但我只能使用 mockito 来做到这一点。请帮我。

标签: javatestingmockingmockito

解决方案


您不能模拟使用new带有mockito.

您必须将数据源创建代码与查询执行分离。

例如,您可以引入工厂模式来实现这一目标。


推荐阅读