单元测试 - 导致测试失败的相对路径?

时间:2017-10-19 09:16:07

标签: java unit-testing jenkins nullpointerexception inputstream

我有一个Java单元测试:

@Test
public void shouldCreateCorectPerson() throws IOException, ParseException {

    //test data
    Person expectedPerson = createExpectedObject(PersonsTest.class.getResourceAsStream("/com/my/package/personStub/person1Stub.json"));

    //other code and asserts...


}


       protected static Person createExpectedPerson(InputStream inputStream) throws IOException {

        Gson gson = new Gson();
        Person expectedPerson = gson.fromJson(IOUtils.toString(inputStream, StandardCharsets.UTF_8), Person.class);
        return expectedPerson;
    }

当我在Intelij本地运行此测试时,它按预期工作,但是当我在jenkins中运行它失败时,是否由于我使用相对路径? e.g:

/com/my/package/personStub/person1Stub.json

如何在jenkins和本地运行时确保找到此文件的路径?

1 个答案:

答案 0 :(得分:1)

当您从构建系统运行测试时假设person1Stub.json在您的类路径中,以下是否有效:

Person expectedPerson = createExpectedObject(PersonsTest.class.getClassLoader().getResourceAsStream("com/my/package/personStub/person1Stub.json"));