在测试Camel路由时使用模拟的dataSourcebean



我在spring-xml中定义了一个dataSourcebean,如下所示

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

现在我想测试一个rest路由,它通过调用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>

我有我的测试类如下,所以现在它工作

@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以进行测试(当它返回null时(
我尝试过类似的东西

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

没有成功。有人能给我一个提示吗?谢谢

最后我找到了问题的根源以及解决方案
首先,voidcall方法应该用doAnswer来模拟,而不是用thenReturn来模拟(显然(
其次,我处理的是存储函数,所以callableStatement上没有调用getResultSet方法,而是调用了getObject方法,所以这应该被模拟为

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

最新更新