Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions should I test get() and set() methods?

I could not confirm whether to do these tests. It seems the set and get method is so simple,such as:

setA(String A) {
    this.A = A;
} 

getA(){
    return A;
}

Any ideas would be appreciated!

Thanks, Joseph

like image 639
Joseph Avatar asked Dec 02 '22 05:12

Joseph


1 Answers

I've only seen a very few problems with getters and setters in the wild, and only one of those could have been detected via a unit test, and only then if all of the getters and setters were tested together, rather than by individual test methods.

Consider the copy/paste mistake of reusing the same field from two different pairs of getters/setters. I.e.,

public void setA(Object a) {
  this.a = a;
}
public Object getA() {
  return a;
}

public void setB(Object a) {
  this.a = a;
}
public Object getB() {
  return a;
}

Unit tests that focus on one setter/getter pair at a time won't expose the problem.

Modern IDEs will generate getters and setters on request, so this mistake is unlikely, but not everyone uses modern IDEs. (A vi user created the bug above.) And if these methods reside in a simple data-holder object, the problem may only show up a bit far from the cause.

For this reason, if I test getters and setters at all (and I often don't), it's from a single test method that calls all of the setters first with distinct values, then asserts on all of the getters.

One problem you've got to live with, though, is that there's no guarantee that a method that starts life as a "simple" getter or setter will stay that way when someone else gets their hands on the code and decides, say, that a getter is a good place do something that involves a side-effect.

like image 172
Dave W. Smith Avatar answered Dec 06 '22 09:12

Dave W. Smith