If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Thursday, March 13, 2014

Ceylon: creating testdata is a breeze

/**
In java it's really difficult to create complex objects for unit testing. There have been some attempts to
workaround this difficulty like using
- Object mothers --> factories to create objects (this becomes messy very quickly as well)
- Test Data builders --> http://java.dzone.com/articles/creating-objects-java-unit-tes
In Ceylon it becomes really easy to create testdata in an easy fashion as we will see.
We just make use of named arguments to construct our objects.
**/
shared class Car(engine, radio, tires) {
shared Engine engine;
shared Radio radio;
shared {Tire*} tires;
shared actual String string =>
"Car {
engine=``engine``
radio=``radio``
tires=``tires``
}";
}
shared class Engine(shared Float horsepower) {
shared actual String string => "Engine(``horsepower``)";
}
shared class Radio(shared String type) {
shared actual String string => "Radio(``type``)";
}
shared class Tire(shared String brand) {
shared actual String string => "Tire(``brand``)";
}
/**
Using the multiline string representation of Car we get a really nicely
formatted output :)
Car {
engine=Engine(150.0)
radio=Radio(FM)
tires=[Tire(Pirelli), Tire(Pirelli), Tire(Pirelli), Tire(Pirelli)]
}
**/
void demoCreatingTestData() {
Car car = Car {
engine = Engine(150.0);
radio = Radio("FM");
tires = {Tire("Pirelli"),Tire("Pirelli"),Tire("Pirelli"),Tire("Pirelli")};
};
print(car);
}

No comments:

Post a Comment