繁体   English   中英

Spring jdbcTemplate单​​元测试

[英]Spring jdbcTemplate unit testing

我是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实现这一点有任何建议?

非常感谢你提前!

如果你想进行纯单元测试,那么就行了

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

您将需要模拟Service,然后使用service.getJdbcTemplate()方法返回模拟JdbcTemplate对象,然后模拟模拟JdbcTemplate的查询方法以返回所需的List。 像这样的东西:

@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。

您需要使用Spring Test来执行此操作。 看看文档:

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

你需要使用@RunWith创建一个测试,并使用带有@ContextConfiguration的spring conf:

@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声明应用程序上下文资源位置或将用于加载上下文的带注释的类。 希望能有所帮助

希望能有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM