I'm creating a test which takes it's data from an external source, in my case a json file. I'm using JUnit Parameterized for data injection in the corresponding fields.
@RunWith(Parameterized.class)
public class MyTest extends CommonTest
{
@Parameterized.Parameter
public String field1;
@Parameterized.Parameter(1)
public String field2;
public static Collection<Object[]> params() throws PropertyNotFoundException
{
final JsonReader reader = new JsonReader(new FileReader("path to the json file"));
// here I am reading the tests sampledata from the json file
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-spring.xml"})
@ActiveProfiles(resolver = SpringActiveProfileResolver.class)
public class CommonTest
{
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
...
}
For the moment I use a static path to the external source in the params() method. How can I use a relative path to this external source and not have it hardcoded? The json file is next to the test-spring.xml
My issue here is that the params() method is static and can't inject something through Spring to solve it.
How can I address this issue?
I see that test-spring.xml
is at the root of your classpath, so if the json file is also, then you can get file handle like this...
Resource resource = new ClassPathResource("/file.json");
File file = resource.getFile();
You may also want to take a look at ClassRelativeResourceLoader if you want to keep the json file next to your test class