Spring jdbcTemplate单元测试

10

我是Spring的新手,对JUnit和Mockito有一些经验。

我有一个需要进行单元测试的方法:

public static String getUserNames(final String userName {
  List<String> results = new LinkedList<String>();
   results =  service.getJdbcTemplate().query("SELECT USERNAME FROM USERNAMES WHERE NAME = ?", new RowMapper<String>() {
      @Override
      public String mapRow(ResultSet rs, int rowNum) throws SQLException {
          return new String(rs.getString("USERNAME");
      }
   }

   return results.get(0);      
   },userName)

请问有人可以提供使用JUnit和Mockito实现这个功能的建议吗?

非常感谢您的帮助!


1
您需要定义一个测试应用上下文,SpringJUnit4ClassRunner将会选择此上下文。我看到您正在尝试进行集成测试而不是单元测试,这两者是不同的。 - Vaelyr
1
你想测试方法的哪些方面?你尝试编写了哪些测试?请展示一些工作。 - La-comadreja
你可以看看 Acolyte 框架用于 JDBC 单元测试。 - cchantep
2个回答

18

如果您想进行纯单元测试,则针对该行执行

service.getJdbcTemplate().query("....");

您需要模拟服务,然后模拟service.getJdbcTemplate()方法返回一个模拟的JdbcTemplate对象,然后模拟mocked JdbcTemplate的查询方法以返回所需的列表。类似这样:

@Mock
Service service;

@Mock
JdbcTemplate jdbcTemplate;


@Test
public void testGetUserNames() {

    List<String> userNames = new ArrayList<String>();
    userNames.add("bob");

    when(service.getJdbcTemplate()).thenReturn(jdbcTemplate);
    when(jdbcTemplate.query(anyString(), anyObject()).thenReturn(userNames);

    String retVal = Class.getUserNames("test");
    assertEquals("bob", retVal);
}

上述内容不需要任何Spring支持。如果您正在进行集成测试,并且实际上想要测试从数据库中正确获取数据,那么您可能希望使用Spring Test Runner。


我得到了以下异常。我按照这个链接做的一样。http://stackoverflow.com/questions/38374823/spring-jdbctemplate-junit - Javadroider

1
你需要使用Spring Test来完成这个任务。请查看文档:

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html

您需要使用 @RunWith 创建一个测试,并使用 @ContextConfiguration 使用您的 spring 配置:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class SpringAppTests {
    @Autowired
    private HelloService helloService;

    @Test
    public void testSayHello() {
        Assert.assertEquals("Hello world!", helloService.sayHello());
    }
}

以下是来自文档的简要说明:

@Runwith

使用@RunWith(SpringJUnit4ClassRunner.class),开发人员可以实现标准的JUnit 4.4单元和集成测试,并同时获得TestContext框架的好处,例如支持加载应用程序上下文、测试实例的依赖注入、事务性测试方法执行等。

@ContextConfiguration

@ContextConfiguration定义了类级别的元数据,用于确定如何为集成测试加载和配置ApplicationContext。具体而言,@ContextConfiguration声明将用于加载上下文的应用程序上下文资源位置或带注释的类。希望能帮到您。

希望对您有所帮助。


谢谢Fede..我想我需要更明确我想要实现什么...我想知道是否可能使用JUnit和Mockito模拟jdbcTemplate.query方法的返回值...谢谢 - Mat
@Mat 对于误解你的需求我感到抱歉。如果你想要,我可以删除这个答案。顺便说一下,在这种情况下你需要使用mockito,你可以看看这个页面http://gojko.net/2009/10/23/mockito-in-six-easy-examples/。 - Federico Piazza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接