Excel data loader utility for JUnit
You need a Function<Row,POJO>
which maps an Excel row into a POJO or your choice:
Function<Row, Input> pojoMapper() {
return (row) -> {
Iterator<Cell> cells = row.cellIterator();
return new Input(
asLong(cells.next()),
asLong(cells.next()),
asLong(cells.next()));
};
}
Here a the Input
POJO from this example:
public class Input {
private long a;
private long b;
private long result;
public Input(long a, long b, long result) {
this.a = a;
this.b = b;
this.result = result;
}
//...
With this seatup you can automatically load excel sheets from folders according to the following convention: src/test/resources/{use-case}/{test-class}.
The method com.airhacks.sheetfit.ExcelReader.load
will automatically try to find the Excel sheet and transform the rows into a Stream
of your POJOs.
Particularly useful is the combination with parameterized tests:
@RunWith(Parameterized.class)
public class CalculatorTest {
@Parameters(name = "multiplication with {index} {0}.xslx {1}.xslx")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"evolved", "first"},
{"simple", "second"}
});
}
//the folder
@Parameter(0)
public String useCase;
//file name without the .xslx ending
@Parameter(1)
public String section;
private Calculator cut;
@Before
public void init() {
this.cut = new Calculator();
}
@Test
public void calculations() {
Stream<Input> tests = ExcelReader.load(pojoMapper(), true, 0, this.getClass(), useCase, section);
tests.filter(i -> this.cut.multiply(i.getA(), i.getB()) != i.getResult()).
map(i -> i.toString()).
forEach(Assert::fail);
}
Function<Row, Input> pojoMapper() {
return (row) -> {
Iterator<Cell> cells = row.cellIterator();
return new Input(
asLong(cells.next()),
asLong(cells.next()),
asLong(cells.next()));
};
}
}
The example was borrowed from https://github.com/AdamBien/sheetfit/tree/master/sheetfit-st
<dependency>
<groupId>com.airhacks</groupId>
<artifactId>sheetfit</artifactId>
<version>0.0.1</version>
</dependency>
Checkout http://javaeetesting.com or come to MUC: http://workshops.adam-bien.com/about-testing.htm