【问题标题】:Spring jdbcTemplate unit testingSpring jdbcTemplate 单元测试
【发布时间】:2023-03-22 08:37:01
【问题描述】:

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

提前非常感谢您!

【问题讨论】:

  • 您需要定义测试应用程序上下文,SpringJUnit4ClassRunner 将在其中拾取。正如我所见,您正在尝试执行集成测试而不是单元测试。这是两个不同的东西。
  • 您想测试该方法的哪些方面?您尝试编写哪些测试?展示一些作品。
  • 你可以看看Acolyte JDBC 单元测试框架

标签: java spring unit-testing junit mockito


【解决方案1】:

如果你想做一个纯粹的单元测试,那么对于这一行

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

你需要mock这个Service,然后service.getJdbcTemplate()方法返回一个mock JdbcTemplate对象,然后mock这个mocked 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。

【讨论】:

【解决方案2】:

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

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

您需要使用@RunWith 创建一个测试并将您的spring conf 与@ContextConfiguration 一起使用:

@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 模拟 jdbcTemplate.query 方法的返回和 Mockito...谢谢
  • @Mat 抱歉误会您需要。如果你愿意,我可以删除答案。顺便说一句,在那种情况下你需要 mockito,你可以看看这个页面gojko.net/2009/10/23/mockito-in-six-easy-examples
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
  • 2016-05-28
相关资源
最近更新 更多