Contents
Do getters and setters need unit tests?
Properties (getters/setters in Java) are good examples of code that usually doesn’t contain any logic, and doesn’t require testing.
Is unit testing always necessary?
Unit tests are also especially useful when it comes to refactoring or re-writing a piece a code. If you have good unit tests coverage, you can refactor with confidence. Without unit tests, it is often hard to ensure the you didn’t break anything. In short – yes.
Do you need getters and setters if you have a constructor?
You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because – well – nothing else will. The only way to guarantee initialising the fields is to assign them.
Can you use setters in constructor?
Avoiding setters in constructors makes it clear that the only thing the constructor is doing is setting the instance variable and skipping any other behavior that happens in the setter.
When to write unit tests for setters and getters?
I would say don’t write unit tests for setters and getters, unless your setters and getters contain program logic (something getting computed as the setter or getter is called). On a real project you will have more than plenty program logic to unit test without having to test something trivial like setters and getters.
What’s the difference between unit tests and getters?
Unit tests are there to test the behaviour of your code, in an expressive and meaningful way, and getters/setters are only a means to an end. If you tests use the getters/setters to achieve their goal of testing the “real” functionality, then that’s good enough.
Do you have to test getters and setters in Java?
On a real project you will have more than plenty program logic to unit test without having to test something trivial like setters and getters. Roy Osherove in his famous book ‘The Art Of Unit Testing’ says: Properties (getters/setters in Java) are good examples of code that usually doesn’t contain any logic, and doesn’t require testing.
Can a getter and setter be automatically generated?
However getters and setters can be automatically generated, they typically only contain one line in the method and if they cause your code to fail you probably have bigger problems. It’s not common practise with unit testing to bother testing the getters and setters and you can avoid testing them and your unit testing will still be comprehensive.