如何模拟JdbcTemplate.queryForObject()方法

时间:2012-12-11 10:51:48

标签: java mockito jmock jmockit springmockito

我的方法如下:

public class Decompile extends JdbcDaoSupport
public void getRunner(){
String val = this.getJdbcTemplate().queryForObject(sql,String.class, new Object[]{1001});
}
}

请建议我如何嘲笑这个。

5 个答案:

答案 0 :(得分:7)

@Mock
JdbcTemplate jdbctemplate;

@Test
public void testRun(){
when(jdbctemplate.queryForObject(anyString(),eq(String.class),anyObject()).thenReturn("data");
}

答案 1 :(得分:3)

EasyMock-3.0示例

    String sql = "select * from t1";
    Object[] params = new Object[] { 1001 };
    JdbcTemplate t = EasyMock.createMock(JdbcTemplate.class);
    EasyMock.expect(
            t.queryForObject(sql, String.class, params)).andReturn("res");
    EasyMock.replay(t);

答案 2 :(得分:2)

使用JMockit,代码将如下:

@Mocked
JdbcTemplate jdbcTemplate


new Expectations() {
    jdbcTemplate.queryForObject(sql,String.class, new Object[]{1001});
    result = "result you want";
}

有关JMockit的更多信息是here

答案 3 :(得分:1)

使用Mockito,您还可以按如下方式模拟queryForObject(..)方法:

@Mock
JdbcTemplate jdbctemplate;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testRun(){
  when(jdbctemplate.queryForObject(eq("input string"), refEq(new Object[]{1001}), eq(String.class))).thenReturn("data");
}

其他一些信息来源 - http://sourcesnippets.blogspot.com/2013/06/jdbc-dao-unit-test-using-mockito.html

答案 4 :(得分:0)

以下是我在测试类似方法时使用的工作代码

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;

@RunWith(MockitoJUnitRunner.class)
public class DecompileTest {

    @Mock/* works fine with autowired dependency too */
    JdbcTemplate jdbcTemplate;

    @InjectMocks/* for the claa that we are mocking */
    Decompile testclass;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testgetRunner() {
        Mockito.lenient().when(jdbcTemplate.queryForObject("select * from .. ",String.class, new Object[] { 1001 } )).thenReturn("resultval");
        testclass.getRunner();
    }

}

mvn 包使用如下(与 spring 版本兼容 > 2 /* 测试 */ )

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-test</artifactId> 
    <scope>test</scope> 
</dependency> 

<dependency>
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-test</artifactId> 
    <scope>test</scope> 
</dependency>