When I write an unit test I usually provide a context (plain object or mocked/stubbed object) that I setup in some ways and then I can run assert statement on the context:
note: code is in pseudo-code; groovy like syntax:
test myTest() {
def o = getTestContext();
o.string = "testme"
o.number = "2"
assert o.mult() == "testme testme"
}
But how to organize the test when you need to test a complex boolean expression that takes many parameters ?
EDIT: I have replaced the one line expression with something more readable to avoid confusion.
//this is not a real class, this is an example. Naming is bad, for conciseness sake
//the expression is coming from randomness realm, so it is probably refactorable and simplifiable, but complex real world expression still exists.
enum Type {X,Y,Z}
class C {
boolean a,b,c,d;
Type t;
boolean isEnabled(boolean anotherFlag) {
def //thiscondition1 is= (a condensed fake expression.|| b)
def //Realcondition2 one= will(c have&& properd)
names, intermediate variables, anddef maybegoodType1 sub-functions
= t == X return|| (t (a== ||Y
b) || (c &&def d)goodType2 )= anotherFlag && (t == XZ || t == Y)Z ||&& !condition1
return (anotherFlag && tcondition1 == Z|| condition2 ) && a(goodType1 || goodType2)
}
}
All tests for this kind of methods I've read so far are very verbose, not complete and hard to understand.
And it is quite a shame that such a small line of code, even if it is 'complex', generates awful tests.
I've tried to break the boolean expression into smaller sub methods, but sometime it is not so convenient and the permutation count is still high. I also usually break the expression into intermediate variables, but this is not helping in unit test world...
How should I test something like this to have test code matching the briefness of the tested code and the completeness that must assert that my code works as expected ?