在测试 Camel 路由时使用模拟数据源 bean

Using mocked dataSource bean when testing Camel route

我在 spring xml 中定义了一个数据源 bean,如下所示

<bean id="apacheBasicDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" >
    <property name="url" value="jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = myservice)))" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
    ...
</bean>

现在我想测试一个休息路线,它通过在 groovy 脚本

中调用存储过程来完成他的工作
<get uri="/utils/foo" produces="text/xml">
    <route id="utils.foo">
        <setBody>
            <groovy>
                import groovy.sql.Sql
                def sql = Sql.newInstance(camelContext.getRegistry().lookupByName('apacheBasicDataSource'))
                res = request.getHeader('invalues').every { invalue ->
                    sql.call("{? = call my_pkg.mapToSomeValue(?)}", [Sql.VARCHAR, invalue]) {
                        outValue -> do some stuff..
                    }
                }
                sql.close()
                new StringBuilder().append(
                    some stuff..
                )
            </groovy>
        </setBody>
    </route>
</get>

我的测试class如下,所以现在可以了

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = {"classpath:camel.xml"})
public class EdiapiApplicationNewTest {

    @Autowired
    private CamelContext context;

    @MockBean private DataSource dataSource;
    @Mock private CallableStatement callableStatement;
    @Mock private Connection connection;
    @Mock private ResultSet resultSet;

    @Test
    public void testSimple() throws Exception {

        when(callableStatement.getResultSet()).thenReturn(resultSet);
        when(dataSource.getConnection()).thenReturn(connection);
        when(connection.prepareCall(anyString())).thenReturn(callableStatement);

        context.getRegistry().bind("apacheBasicDataSource", dataSource);

        TestRestTemplate restTemplate = new TestRestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/utils/foo?invalues=foo,bar", String.class);
        Assert.assertEquals("<value>false</value>", response.getBody());
    }
}

但我希望能够使用一些自定义值来填充模拟的 ResultSet 以进行测试(目前它 returns null)
我试过类似

when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getString(anyInt())).thenReturn("some value");

没有成功。有人可以给我一个提示吗? 谢谢!

终于找到了问题的根源和解决方法。
首先,void call 方法应该用 doAnswer 而不是 thenReturn 来模拟(很明显)。
其次,我处理了存储函数,所以没有 getResultSet 方法调用 callableStatement,而是调用了 getObject 方法,所以这应该被模拟为

when(callableStatement.getObject(1)).thenAnswer(inv -> "some custom value");