我正在使用Wiremock运行Spring Boot应用程序。我的文件结构是这样的:
project/main/
- java/package/Wiremock.java
- resources/wiremock/__files/file.json
在Wiremock.java内部,我这样调用WireMockServer:
WireMockServer wiremockServer = new WireMockServer(WireMockConfiguration.wireMockConfig()
.withRootDirectory(getClass().getResource("/wiremock").getPath())
.port(port));
wiremockServer.start();
wiremockServer.stubFor(get(urlEqualTo("/myurl"))
.willReturn(aResponse()
.withBodyFile("file.json")
.withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.withStatus(HTTP_OK)));
当我在本地运行它时,它可以按预期运行。
当我将应用程序编译为jar文件时,将使用以下结构生成一个jar文件/Users/user/project-0.0.1-SNAPSHOT.jar:
BOOT-INF/classes/
- wiremock/__files/file.json
- package/Wiremock.class
但是当我运行jar文件时,出现以下错误:
java.lang.RuntimeException: java.io.FileNotFoundException: /Users/user/jar:file:/Users/user/project-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/wiremock/__files/file.json (No such file or directory)
请帮助,谢谢
答案 0 :(得分:0)
此路径正确吗?
/Users/user/jar:file:/Users/user/project-0.0.1-SNAPSHOT.jar!/BOOT- INF / classes!/ wiremock / __ files / file.json(无此文件或目录)
我发现还有一个“!”在XXXX.jar和类之后。
答案 1 :(得分:0)
我今天遇到了同样的问题,当我在IDEA中运行电线模拟时,它可以工作。但是,当我通过java -jar模式运行该应用程序时,有线模拟服务器无法找到json模拟文件。此问题的根本原因是,在初始化有线模拟服务器时,它将通过com.github.tomakehurst.wiremock.common.ClasspathFileSource
找到json文件。
类,它将以递归方式将文件添加到您指定的配置路径列表中。添加文件的逻辑如下所示。
public List<TextFile> listFilesRecursively() {
if (this.isFileSystem()) {
this.assertExistsAndIsDirectory();
List<File> fileList = Lists.newArrayList();
this.recursivelyAddFilesToList(this.rootDirectory, fileList);
return this.toTextFileList(fileList);
} else {
return FluentIterable.from(toIterable(this.zipFile.entries())).filter(new Predicate<ZipEntry>() {
public boolean apply(ZipEntry jarEntry) {
return !jarEntry.isDirectory() && jarEntry.getName().startsWith(ClasspathFileSource.this.path);
}
}).transform(new Function<ZipEntry, TextFile>() {
public TextFile apply(ZipEntry jarEntry) {
return new TextFile(ClasspathFileSource.this.getUriFor(jarEntry));
}
}).toList();
}
}
它将以递归方式添加绝对以路径开头的文件。但是当您使用java -jar运行时,jarEntry.getName以'BOOT-INF'开始。解决方案之一是用子类重写该方法,并扩展ClasspathFileSource,然后修改匹配规则。它会解决