ProgramingTip

테스트 파일을 JUnit으로 가져 오는 쉬운 방법

bestdevel 2020. 10. 18. 18:55
반응형

테스트 파일을 JUnit으로 가져 오는 쉬운 방법


junit 클래스에서 String / InputStream / File / etc 유형으로 파일에 대한 참조를 얻는 쉬운 방법을 제안 할 수있는 누군가 테스트 클래스에서? 분명히 (이 경우 xml)을 대량으로 어디에 넣거나 파일로 읽을 수 있습니다. Junit 전용 바로 가기가 파일입니까?

public class MyTestClass{

@Resource(path="something.xml")
File myTestFile;

@Test
public void toSomeTest(){
...
}

}

@Rule주석 을 사용해 볼 수 있습니다 . 다음은 문서의 예입니다.

public static class UsesExternalResource {
    Server myServer = new Server();

    @Rule public ExternalResource resource = new ExternalResource() {
        @Override
        protected void before() throws Throwable {
            myServer.connect();
        };

        @Override
        protected void after() {
            myServer.disconnect();
        };
    };

    @Test public void testFoo() {
        new Client().run(myServer);
    }
}

FileResource클래스 확장 을 생성하기 만하면 ExternalResource됩니다.

전체 예

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class TestSomething
{
    @Rule
    public ResourceFile res = new ResourceFile("/res.txt");

    @Test
    public void test() throws Exception
    {
        assertTrue(res.getContent().length() > 0);
        assertTrue(res.getFile().exists());
    }
}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.junit.rules.ExternalResource;

public class ResourceFile extends ExternalResource
{
    String res;
    File file = null;
    InputStream stream;

    public ResourceFile(String res)
    {
        this.res = res;
    }

    public File getFile() throws IOException
    {
        if (file == null)
        {
            createFile();
        }
        return file;
    }

    public InputStream getInputStream()
    {
        return stream;
    }

    public InputStream createInputStream()
    {
        return getClass().getResourceAsStream(res);
    }

    public String getContent() throws IOException
    {
        return getContent("utf-8");
    }

    public String getContent(String charSet) throws IOException
    {
        InputStreamReader reader = new InputStreamReader(createInputStream(),
            Charset.forName(charSet));
        char[] tmp = new char[4096];
        StringBuilder b = new StringBuilder();
        try
        {
            while (true)
            {
                int len = reader.read(tmp);
                if (len < 0)
                {
                    break;
                }
                b.append(tmp, 0, len);
            }
            reader.close();
        }
        finally
        {
            reader.close();
        }
        return b.toString();
    }

    @Override
    protected void before() throws Throwable
    {
        super.before();
        stream = getClass().getResourceAsStream(res);
    }

    @Override
    protected void after()
    {
        try
        {
            stream.close();
        }
        catch (IOException e)
        {
            // ignore
        }
        if (file != null)
        {
            file.delete();
        }
        super.after();
    }

    private void createFile() throws IOException
    {
        file = new File(".",res);
        InputStream stream = getClass().getResourceAsStream(res);
        try
        {
            file.createNewFile();
            FileOutputStream ostream = null;
            try
            {
                ostream = new FileOutputStream(file);
                byte[] buffer = new byte[4096];
                while (true)
                {
                    int len = stream.read(buffer);
                    if (len < 0)
                    {
                        break;
                    }
                    ostream.write(buffer, 0, len);
                }
            }
            finally
            {
                if (ostream != null)
                {
                    ostream.close();
                }
            }
        }
        finally
        {
            stream.close();
        }
    }

}


실제로 File객체를 가져와야하는 경우 다음을 수행 할 수 있습니다.

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

이 블로그 게시물에 설명 된대로 크로스 플랫폼 작업의 이점 있습니다.


손으로 파일을 읽고 싶지 않다고 다니는데 이건 꽤 있고

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());
    }
}

해당 파일이 클래스 경로에 있는지 확인하기 만하면됩니다. Maven을 사용하는 경우 파일을 src / test / resources에 넣으면 Maven이 테스트를 실행할 때 클래스 경로에 파일을 포함합니다. 이런 종류의 일을 많이해야한다면 파일을 여는 코드를 수퍼 클래스에 넣고 테스트가 그로부터 상속 받도록 할 수 있습니다.


시도해 볼 수 있습니다.

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

테스트 리소스 파일을 몇 줄의 코드로 추가 종속성없이 문자열로로드하려는 경우 다음과 같이 트릭을 수행합니다.

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\\A").next();
    scanner.close();
    return contents;
}

"\\ A"는 입력의 시작과 일치하며 하나만 있습니다. 따라서 전체 파일 내용을 구문 분석하고 문자열로 반환합니다. 무엇보다도 IOUTils와 같은 타사 라이브러리가 필요하지 않습니다.

참고 URL : https://stackoverflow.com/questions/2597271/easy-way-to-get-a-test-file-into-junit

반응형