使用Mockito模拟JdbcTemplate的DataSource [英] Mocking DataSource for JdbcTemplate with Mockito

查看:364
本文介绍了使用Mockito模拟JdbcTemplate的DataSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Spring项目中测试一个类。我想在测试类和dao类中尽可能多地进行更改,这样我就不必因为更改而重新测试所有类型的东西。

I'm trying to test a class in a Spring project. I would like to make as many changes as possible in the test class vs. the dao class so that I don't have to retest all sorts things because of a change.

我正在使用的类有一个 JdbcTemplate模板类变量,该变量由以下实例化:

The class I'm working with has a JdbcTemplate template class variable that is instantiated by the following:

setJdbcTemplate(DataSource dataSource) {
    this.template = new JdbcTemplate(dataSource);
}

我想测试的方法是一个模板.query(< code>)运行已定义的SQL查询并将结果返回到列表。

The method I would like to test makes a template.query(<code>) to run a defined SQL query and return the results to a list.

我在测试用例中创建了以下内容,但我不确定如何使用它。我是否可以使用Mockito使以下代码返回某个字符串列表?

I created the following in my test case, but I'm not sure how to put it into use. Can I make the following code return a certain list of Strings using Mockito?

DataSource mockedDataSrc = Mockito.mock(DataSource.class);
customerClassDao.setJdbcTemplate(mockedDataSrc); 

我可以以某种方式在或其他时使用命令设置我想要返回到JdbcTemplate的 .query 调用?

Can I somehow use the when or another command to set what I want to be returned to the JdbcTemplate's .query call?

推荐答案

您无法执行此操作,因为您无法控制 JdbcTemplate 实现。您应该依赖注入 JdbcTemplate ,然后模拟 JdbcTemplate

You can't do this because you don't have control over the JdbcTemplate implementation. You should dependency inject the JdbcTemplate and then mock the JdbcTemplate instead.

这个难点指出代码存在问题。您的代码取决于 JdbcTemplate 的具体实例。如果你在它上面使用了依赖注入,它会更少耦合。

This difficulty is pointing out a problem with your code. Your code depends on the concrete instance of JdbcTemplate. It would be less coupled if you used Dependency Injection on it instead.

因为你不想修改你的系统在测试中,你可以这样做:

Since you don't want to modify your system under test, you can do this:

更改模板字段,使其受到包保护(即:删除私有关键词)。然后,在实例化您正在测试的类之后,我将其设置为mock(JdbcTemplate.class)。现在,您将能够直接使用JdbcTemplate并在JdbcTemplate上进行验证。

Change the template field so it's package protected (ie: remove the private keyword). Then, I'd set it to be a mock(JdbcTemplate.class) after you instantiate the class you're testing. Now you'll be able to use when and verify on the JdbcTemplate directly like you wanted originally.

因此,您正在测试的类将如下所示:

So the class you're testing will look like this:

public class SystemUnderTest {

JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(DataSource dataSource) {
        this.template = new JdbcTemplate(dataSource);
    }

}

您的测试将执行以下操作:

And your test will do this:

@Before
public void setUp() {
    SystemUnderTest sut = new SystemUnderTest();
    sut.jdbcTemplate = mock(JdbcTemplate.class);                
}

// ...

这篇关于使用Mockito模拟JdbcTemplate的DataSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆