I am working a project with an structure similar to what you mentioned.
I put all my server responses in a file under resources
folder like app/src/test/resources/BookingInfo.json
.
All java test files are under app/src/test/java/PACKAGE_NAME
similar to what you said. I have a Fixture
class under a package that contains name of resources:
@SuppressWarnings("nls")
public final class Fixtures
{
public static final String GET_ANNOUNCEMENT = "GetAnnouncement.json";
...
}
And finally a FixtureUtils class that a method of this class is responsible to read resource file and return result.
import java.nio.file.Files;
import java.nio.file.Paths;
public class FixtureUtils
{
public static final AFixture fixtureFromName(final String fixtureName)
{
final String fixtureString = FixtureUtils.stringFromAsset(fixtureName);
if (StringUtils.isEmpty(fixtureString))
{
return null;
}
final Gson gson = new Gson();
final AFixture aFixture = gson.fromJson(fixtureString, AFixture.class);
return aFixture;
}
private static final String stringFromAsset(final String filename)
{
try
{
final URL resourceURL = ClassLoader.getSystemResource(filename);
if (resourceURL == null)
{
return null;
}
final String result = new String(Files.readAllBytes(Paths.get(resourceURL.toURI())),
Charset.forName("UTF-8")); //$NON-NLS-1$
return result;
}
catch (final Exception e)
{
e.printStackTrace();
}
return null;
}
private FixtureUtils()
{
// Ensure Singleton
}
}
And AFixture
class looks like:
public class AFixture
{
public List<JsonElement> validItems;
public List<JsonElement> invalidItems;
public AFixture()
{
super();
}
public List<JsonElement> getInvalidItems()
{
return this.invalidItems;
}
public List<JsonElement> getValidItems()
{
return this.validItems;
}
public void setInvalidItems(final List<JsonElement> invalidItems)
{
this.invalidItems = invalidItems;
}
public void setValidItems(final List<JsonElement> validItems)
{
this.validItems = validItems;
}
}
Note: java.nio.file
has been removed from JDK8 if I'm not mistaken however you have no problem if you are using JDK7. If you are using JDK8 then you just need to change stringFromAsset
method in such a way like FileInputStream (old fashion style) or Scanner.