io.github.sskorol.data.TestDataReader Maven / Gradle / Ivy
package io.github.sskorol.data;
import one.util.streamex.StreamEx;
import java.util.Objects;
import static org.joor.Reflect.on;
/**
* Generic structure for reading test data in JSON, CSV and YAML formats. Each format has it's own implementation,
* which should be passed to {@link #use(Class)} method.
* {@code
* use(CsvReader.class).withTarget(User.class).withSource("users.csv").read();
* use(YamlReader.class).withTarget(TravisConfiguration.class).read();
* use(JsonReader.class).withTarget(Animal.class).withSource("http://animals.json").read();
* }
* Please note that {@link io.github.sskorol.data.TestDataReader.DataBuilder#withSource(String)} is optional. But if
* it's skipped, you have to use {@link io.github.sskorol.data.Source} annotation to define source path.
*
* @param {@link io.github.sskorol.data.DataReader} implementation class.
*/
public class TestDataReader> {
private final Class dataReaderClass;
public TestDataReader(final Class dataReaderClass) {
this.dataReaderClass = dataReaderClass;
}
public static > TestDataReader use(final Class dataReaderClass) {
return new TestDataReader<>(dataReaderClass);
}
public DataBuilder withTarget(final Class entityClass) {
return new DataBuilder<>(dataReaderClass, entityClass);
}
public static class DataBuilder {
private final Class dataReaderClass;
private final Class entityClass;
private String path;
public DataBuilder(final Class dataReaderClass, final Class entityClass) {
this.dataReaderClass = dataReaderClass;
this.entityClass = entityClass;
}
public DataBuilder withSource(final String path) {
this.path = path;
return this;
}
public StreamEx read() {
var args = StreamEx.of(entityClass, path).filter(Objects::nonNull).toArray();
return on(dataReaderClass).create(args).call("read").get();
}
}
}