Easy way to get a test file into JUnit

前端 未结 5 1786
面向向阳花
面向向阳花 2020-12-08 04:04

Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in t

5条回答
  •  自闭症患者
    2020-12-08 04:12

    I know you said you didn't want to read the file in by hand, but this is pretty easy

    public class FooTest
    {
        private BufferedReader in = null;
    
        @Before
        public void setup()
            throws IOException
        {
            in = new BufferedReader(
                new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
        }
    
        @After
        public void teardown()
            throws IOException
        {
            if (in != null)
            {
                in.close();
            }
    
            in = null;
        }
    
        @Test
        public void testFoo()
            throws IOException
        {
            String line = in.readLine();
    
            assertThat(line, notNullValue());
        }
    }
    

    All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

提交回复
热议问题