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

5 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 AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay