You can try the @Rule annotation. Here is an example from the docs:
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); } }
You just need to create a FileResource class that extends ExternalResource .
Full example
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) {
Ha Apr 08 '10 at 5:44 2010-04-08 05:44
source share