我的方法如下所示:
public class Decompile extends JdbcDaoSupport
public void getRunner(){
String val = this.getJdbcTemplate().queryForObject(sql,String.class, new Object[]{1001});
}
}
请建议我将如何嘲笑这一点。
我的方法如下所示:
public class Decompile extends JdbcDaoSupport
public void getRunner(){
String val = this.getJdbcTemplate().queryForObject(sql,String.class, new Object[]{1001});
}
}
请建议我将如何嘲笑这一点。
@Mock
JdbcTemplate jdbctemplate;
@Test
public void testRun(){
when(jdbctemplate.queryForObject(anyString(),eq(String.class),anyObject()).thenReturn("data");
}
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);
使用JMockit,代码会是这样的:
@Mocked
JdbcTemplate jdbcTemplate
new Expectations() {
jdbcTemplate.queryForObject(sql,String.class, new Object[]{1001});
result = "result you want";
}
关于 JMockit 的更多信息在这里。
使用 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
以下是我在测试类似方法时使用的工作代码
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>