問(wèn)題描述
我正在嘗試在 Spring 項(xiàng)目中測(cè)試一個(gè)類(lèi).我想在測(cè)試類(lèi)與 dao 類(lèi)中進(jìn)行盡可能多的更改,這樣我就不必因?yàn)楦亩匦聹y(cè)試各種東西.
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.
我正在使用的類(lèi)有一個(gè)由以下實(shí)例化的 JdbcTemplate 模板
類(lèi)變量:
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);
}
我想測(cè)試的方法使用 template.query(<code>)
來(lái)運(yùn)行已定義的 SQL 查詢(xún)并將結(jié)果返回到列表.
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.
我在我的測(cè)試用例中創(chuàng)建了以下內(nèi)容,但我不確定如何使用它.我可以使用 Mockito 使以下代碼返回某個(gè)字符串列表嗎?
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
或其他命令來(lái)設(shè)置我想要返回給 JdbcTemplate 的 .query
調(diào)用的內(nèi)容?
Can I somehow use the when
or another command to set what I want to be returned to the JdbcTemplate's .query
call?
推薦答案
您不能這樣做,因?yàn)槟鸁o(wú)法控制 JdbcTemplate
實(shí)現(xiàn).您應(yīng)該依賴(lài)注入 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.
這個(gè)困難是指出你的代碼有問(wèn)題.您的代碼取決于 JdbcTemplate
的具體實(shí)例.如果你在它上面使用依賴(lài)注入,它的耦合會(huì)更少.
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.
由于您不想修改被測(cè)系統(tǒng),您可以這樣做:
Since you don't want to modify your system under test, you can do this:
更改 template
字段,使其受到包保護(hù)(即:刪除 private 關(guān)鍵字).然后,在您實(shí)例化您正在測(cè)試的類(lèi)之后,我會(huì)將其設(shè)置為模擬(JdbcTemplate.class).現(xiàn)在您將能夠像您最初想要的那樣直接在 JdbcTemplate 上使用和驗(yàn)證.
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.
所以你正在測(cè)試的類(lèi)將如下所示:
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);
}
}
你的測(cè)試會(huì)這樣做:
@Before
public void setUp() {
SystemUnderTest sut = new SystemUnderTest();
sut.jdbcTemplate = mock(JdbcTemplate.class);
}
// ...
這篇關(guān)于使用 Mockito 模擬 JdbcTemplate 的數(shù)據(jù)源的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!