java - 如何使用 Java 在 Play 框架中读取 JSON 文件

标签 java json junit playframework couchbase

我正在尝试从我的 Play 应用程序中的 test/resources 包中读取 JSON 文件。我收到 com.couchbase.client.java.error.DocumentDoesNotExistException。我相信我的路径不正确,有人可以建议如何采用绝对路径吗?

public class AppControllerTest extends WithApplication {

    @Inject
    AppDaoServiceImpl appDaoServiceImpl;

    private CouchbaseEnvironment env;
    private static Cluster cluster = null;
    private static Bucket bucket = null;
    private String testResources = System.getProperty("java.class.path") + "/test/resources/";

    private static final ALogger logger = Logger.of(AppControllerTest.class);

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Override
    protected Application provideApplication() {
        return new GuiceApplicationBuilder().build();
    }

    @Before
    public void init() {
        env = DefaultCouchbaseEnvironment.create();
        cluster = CouchbaseCluster.create(env, "127.0.0.1:8091");
        bucket = cluster.openBucket("CLUSTER", "admin123");

        try {
            String docId = "ABEBV_common";
            File testResource = new File(testResources + "ABEBV_common.json");
            FileInputStream is = new FileInputStream(testResource);
            JsonNode testData = Json.parse(is);
            RawJsonDocument rawJsonDocument = RawJsonDocument.create(docId, testData.asText());
            bucket.upsert(rawJsonDocument);

        } catch (Exception e) {
        }

    }

    @Test
    public void testGenericData() {
        Http.RequestBuilder request = new Http.RequestBuilder().method(GET).uri("/app/ms/genericdata/ABEBV")
                .header("client_id", "chase");

        Result result = route(app, request);
        assertEquals(OK, result.status());
        assertEquals("application/json", result.contentType().get());
        assertTrue(contentAsString(result).contains("141-GYCVZY"));
    }

    @After
    public void deleteDocuments() {
        bucket.remove("ABEBV_common");
        bucket.close();
        cluster.disconnect();
    }

}

最佳答案

是的,你的路径不正确,System.getProperty("java.class.path")将返回jvm引用的所有java类路径,你必须这样做,而是使用“user.dir”。

private String testResources = System.getProperty("user.dir") + "/test/resources/";

关于java - 如何使用 Java 在 Play 框架中读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58948526/

相关文章:

java - Cucumber-JUnit,有没有办法控制@before和@after标签运行的顺序

java - 使用迭代器和 ArrayList 的具有 10 个记录的多个 ArrayList

javascript - 美味的 JSON 列表问题

java - Spring 3.2 测试,com.jajway 不包含在依赖项中

json - 根据类型 Play Scala 读/写

java - Mockito NullPointerException - 无法识别存储库

java - JUnit 测试上的 "Singleton"

java - 为什么 liblinear 不预测多数类?

java - 我的 Eclipse 中的 android 项目消失了?

java - 返回形成总和的数组元素