I work on a project where we have to create unit tests for all of our simple beans (POJOs). Is there any point to creating a unit test for POJOs if all they consist of is gette
I don't think there's a point to testing simple property getters and setters. The point of unit-testing is not to verify that your compiler works.
However, as soon as you add a conditional, null-check or other non-trivial behavior to your getters and setters (or other methods) I think it's appropriate to add unit tests.
I once spent two hours because of something like this:
int getX()
{
return (x);
}
int getY()
{
return (x); // oops
}
Since it takes almost no time to write the tests for simple getters, I do it now out of habit.
The rule in TDD is "Test everything that could possibly break" Can a getter break? Generally not, so I don't bother to test it. Besides, the code I do test will certainly call the getter so it will be tested.
My personal rule is that I'll write a test for any function that makes a decision, or makes more than a trivial calculation. I won't write a test for i+1
, but I probably will for if (i<0)...
and definitely will for (-b + Math.sqrt(b*b - 4*a*c))/(2*a)
.
BTW, the emphasis on POJO has a different reason behind it. We want the vast quantity of our code written into POJOs that don't depend on the environment they run in. For example, it's hard to test servlets, because they depend upon executing within a container. So we want the servlets to call POJOs that don't depend on their environment and are therefore easy to test.
In my experience, creating unit tests for POJOs with only getters and setters, is just overkill. There are some exceptions, of course, if there is additional logic in the getter/setter like checking for null and doing something special, than I would create a unit test for that.
Also, if there's a bug in the POJO I'd create a unit test for it so we can prevent it from happening again.
POJOs may also contain other functions, such as equals(), hashCode(), compareTo(), and various other functions. It may be useful to know that those functions are working correctly.
I use IntelliJ as an IDE, and it pretty much writes trivial POJO's for me - certainly the constructor and getters/settors. I don't see any point in unit testing this since any bugs will more than likely be in the test code I write.