I’m writing JUnit tests for a service that creates and acts on an entity in a variety of ways. I want my tests to try lots of different combinations of activity. I have something like this:
test1() {
/** create entity **/
/** assert **/
}
test2() {
/** do X to entity **/
/** assert **/
}
test3() {
/** do X again to entity, expect failure **/
/** assert **/
}
test4() {
/** do Y to entity, expect success **/
/** assert **/
}
However, my understanding is I cannot expect JUnit to run the tests in the correct order, and that each test should be totally self contained.
But if I make every test self contained, then there’s a lot of duplicate code, things run rather long, and it’s more difficult to maintain … for example:
test1() {
/** create entity **/
/** assert **/
}
test2() {
/** create entity **/
/** do X to entity **/
/** assert **/
}
test3() {
/** create entity **/
/** do X to entity **/
/** do X again to entity, expect failure **/
/** assert **/
}
test4() {
/** create entity **/
/** do X to entity **/
/** do X again to entity, expect failure **/
/** do Y to entity, expect success **/
/** assert **/
}
… if you follow me.
So my question is, what’s the “correct” way to write these tests so the code is clean and elegant?
Thanks, Rob
You could call a setup method in each test method to handle the duplicate code.
i.e.