6

我的方法如下所示:

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

请建议我将如何嘲笑这一点。

4

5 回答 5

10
@Mock
JdbcTemplate jdbctemplate;

@Test
public void testRun(){
when(jdbctemplate.queryForObject(anyString(),eq(String.class),anyObject()).thenReturn("data");
}
于 2012-12-11T12:20:46.700 回答
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);
于 2012-12-11T12:19:22.513 回答
2

使用JMockit,代码会是这样的:

@Mocked
JdbcTemplate jdbcTemplate


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

关于 JMockit 的更多信息在这里

于 2012-12-11T15:59:31.010 回答
2

使用 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

于 2015-01-27T21:04:08.473 回答
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> 
于 2020-12-22T10:01:49.900 回答