Spring jdbcTemplate 单元测试

Spring jdbcTemplate unit testing(Spring jdbcTemplate 单元测试)
本文介绍了Spring jdbcTemplate 单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我是 Spring 新手,只对 JUnit 和 Mockito 有点经验

I am new to Spring and only somewhat experienced with JUnit and Mockito

我有以下需要单元测试的方法

I have the following method which requires a unit test

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

Does anyone have any suggestions on how I might achieve this using JUnit and Mockito?

提前非常感谢您!

推荐答案

如果你想做一个纯单元测试那就换行

If you want to do a pure unit test then for the line

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

你需要mock这个Service,然后service.getJdbcTemplate()方法返回一个mock JdbcTemplate对象,然后mock这个mocked JdbcTemplate的查询方法返回你需要的List.像这样的:

You will need to mock the Service, then the service.getJdbcTemplate() method to return a mock JdbcTemplate object, then mock the query method of mocked JdbcTemplate to return the List you need. Something like this:

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

The above doesn't require any sort of Spring support. If you were doing an Integration Test where you actually wanted to test that data was being pulled from a DB properly, then you would probably want to use the Spring Test Runner.

这篇关于Spring jdbcTemplate 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)