I remember reading on someone else's post that test code should not be treated as normal code but as small whole programs and that is an idea I really like and would like to refer to when discussing with other engineer colleagues, but is not unanimously shared.
Specially I was referring to it when discussing if test should be refactored as normal code or not, using private functions for example. Some colleagues were encouraging developers to transform test like these:
public test1() {
variable1 = 'value1'
variable2 = 'value2'
variable3 = 'value2'
assert_something1()
assert_something2()
assert_something3()
}
public test2() {
variable1 = 'value1'
variable2 = 'value2'
different_variable3 = 'different_value3'
assert_something1()
assert_something2()
assert_something_different3()
}
Into this:
public test1() {
set_common_variables()
do_common_assertions()
}
public test2() {
set_common_variables()
different_variable3 = 'different_value3'
do_common_assertions()
assert_something_different3()
}
private set_common_variables()
{
variable1 = 'value1'
variable2 = 'value2'
}
private do_common_assertions()
{
assert_something1()
assert_something2()
}
Arguing they were just encouraging basic refactoring rules for a better code readability by avoiding repetition, but I personally think these do not apply here for these reasons:
Test should be meant to be read separately and short, so I think premises and assertions should be together, event if this means repearing code.
The example above would point a refactor need but not in the test itself but in the code, by refactoring the test we may be occluding what is going on.
What are your experiences on this? Do you think tests should be generally treated as normal code or not?