DEV Community

Cover image for How to read file from test resources in java unit test
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

6 2

How to read file from test resources in java unit test

Use the getClass().getClassLoader().getResourceAsStream() to get an InputStream for the wanted resource. In the following snippet we access the bookmark-example.xml file resource, which is placed directly in the src/test/resources folder:

@Test
void shouldUnmarshallXmlToJava() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance("dev.codepal.bookmark");
    final var jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    InputStream inStream = getClass().getClassLoader().getResourceAsStream(
            "bookmark-example.xml");

    JAXBElement<Bookmark> o = (JAXBElement<Bookmark>)jaxbUnmarshaller.unmarshal(inStream);
    Bookmark bookmark = o.getValue();
    assertThat(bookmark.getTitle(), equalTo("CodepediaOrg"));
}
Enter fullscreen mode Exit fullscreen mode

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay