spring-native
spring-native copied to clipboard
springboot + mybatis-native unittest failed
when run app is ok, but when run unittest will failed:
Caused by: java.io.FileNotFoundException: class path resource
[file:/Users/xx/.../target/classes/mybatis/mapper/userMapper.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:199)
at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:609)
... 164 more
In class MyBatisSpringNativeAutoConfiguration
resources = holders.stream()
.flatMap(holder -> holder.getMapperLocations().stream().map(ClassPathResource::new)).toArray(
Resource[]::new);
Because mapperLocations is full file path, the resource can be FileSystemResource can not be ClassPathResource! When in the test project ,mapper files are in test resources,so the full file path can remove the baseUrl,but commons mapper files are in src/main/resource path, so in the method: org.mybatis.spring.nativex.MyBatisScannedResourcesHolder.Registrar#toPath, url.startsWith(baseUrl) is false.
Maybe can change code like this, just change code in org.mybatis.spring.nativex.MyBatisScannedResourcesHolder.Registrar#toPath, the url index "target/test-classes" or "target/classes", remove the prefix.
private static final String TEST_CLASSPATH= "target/test-classes/";
private static final String CLASSPATH= "target/classes/";
private String toPath(Resource resource, String baseUrl) {
try {
String url = resource.getURL().toString();
String path = url;
int indexTestClassPath = url.indexOf(TEST_CLASSPATH);
int indexClassPath = url.indexOf(CLASSPATH);
if (url.startsWith(baseUrl)) {
path = url.replace(baseUrl, "");
} else if (indexTestClassPath > 0) {
path = url.substring(indexTestClassPath+TEST_CLASSPATH.length());
} else if (indexClassPath > 0) {
path = url.substring(indexClassPath+CLASSPATH.length());
...
@cqsuper Can you raise PR for this?