问题描述
我正在尝试在 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);
}
我想测试的方法使用 template.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);
我能否以某种方式使用 when
或其他命令来设置我想要返回给 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:
更改 template
字段,使其受到包保护(即:删除 private 关键字).然后,在您实例化您正在测试的类之后,我会将其设置为模拟(JdbcTemplate.class).现在您将能够像您最初想要的那样直接在 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);
}
}
你的测试会这样做:
@Before
public void setUp() {
SystemUnderTest sut = new SystemUnderTest();
sut.jdbcTemplate = mock(JdbcTemplate.class);
}
// ...
这篇关于使用 Mockito 模拟 JdbcTemplate 的数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!