mybatis 之脚本解析:
测试代码:
@Test
void setParametersThrowsProperException() throws SQLException {
final MappedStatement mappedStatement = getMappedStatement();
final Object parameterObject = null;
final BoundSql boundSql = mock(BoundSql.class);
TypeHandler<Object> typeHandler = mock(TypeHandler.class);
doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), any(), any(JdbcType.class));
ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", typeHandler).build();
List<ParameterMapping> parameterMappings = Collections.singletonList(parameterMapping);
when(boundSql.getParameterMappings()).thenReturn(parameterMappings);
DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
PreparedStatement ps = mock(PreparedStatement.class);
try {
defaultParameterHandler.setParameters(ps);
Assertions.fail("Should have thrown TypeException");
} catch (Exception e) {
Assertions.assertTrue(e instanceof TypeException, "expected TypeException");
Assertions.assertTrue(e.getMessage().contains("mapping: ParameterMapping"));
}
}
MappedStatement getMappedStatement() {
final Configuration config = new Configuration();
final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps(
new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList<ResultMapping>() {
{
add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)).build());
}
}).build());
}
}).build();
}
这里测试首先会获取mappedStatement对象,模拟一个Boundsql 对象和TypeHander 对象,由于我们sqlbuider 有问题,所以这里抛出了异常。
接着我们做parameterMapping映射的问题,由DefaultParameterHandler处理对象,然后进行预处理。

MyBatis脚本解析与异常处理测试
这篇博客详细介绍了MyBatis中脚本解析的测试过程,通过模拟MappedStatement、BoundSql和TypeHandler对象,测试在参数映射时由于SQLBuilder问题导致的异常。在异常处理部分,展示了如何捕获并验证TypeException。此外,还提供了MappedStatement的创建代码,包括ResultMap的构建。
2320

被折叠的 条评论
为什么被折叠?



