У меня есть следующий код
@Repository
public class ServiceImpl implements MyService {
@Autowired
private ConnectionFactory factory;
private List<Map<String, Object>> execute(String source, String schemaName, String query) {
return getJdbcTemplate(source, schemaName).queryForList(query);
}
private JdbcTemplate getJdbcTemplate(String source, String schemaName) {
return new JdbcTemplate(factory.getDataSource(source, schemaName));
}
@Override
public List<Map<String, Object>> findAll(String source, String schemaName) {
String query = "query";
return execute(source, schemaName, query);
}
}
Мой код тестирования
@RunWith(SpringJUnit4ClassRunner.class)
public class ServiceImplTest {
@Mock
private ConnectionFactory connectionFactory;
@Mock
private DataSource dataSource;
@Mock
private JdbcTemplate template;
@InjectMocks
private final ServiceImpl serviceImpl = new ServiceImpl();
@Before
public void setUp() throws Exception {
}
@Test
public final void testFindAll() {
Map<String, Object> map = new HashMap<>();
map.put("k1", "v1");
List<Map<String, Object>> l = new ArrayList<>();
l.add(map);
when(connectionFactory.getDataSource(any(), any())).thenReturn(dataSource);
when(template.queryForList(any())).thenReturn(l);
List<Map<String, Object>> findAllCustomFieldDefs = serviceImpl.findAll(any(), any());
assertNotNull(findAllCustomFieldDefs);
}
Когда я запускаю это, тогда
return getJdbcTemplate(source, schemaName).queryForList(query);
выбрасывает
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: DataSource returned null from getConnection(): dataSource
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:84)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462)
at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:490)