Reputation: 159
I have a generel question about Unit testing. I have read some guides about unit testing, however i still have one question. What parts of my code do i have to test? For example the class bellow has some variables to be set and a list that is frequently filled, but does it make sense to test them in a JUnitClass? Which part would you test?
public class Bill implements interfaces.Bill {
int billNumber;
Set<Scanable> scans = new LinkedHashSet();
public Bill(int billNumber) {
this.billNumber = billNumber;
}
public void addItem(Scanable s) {
scans.add(s);
}
@Override
public float getSum() {
int sum = 0;
for(Scanable x : this.scans) {
sum += x.getPrice();
}
return sum;
}
@Override
public Set<Scanable> getItems() {
return scans;
}
}
Upvotes: 1
Views: 244
Reputation: 770
In general, unit test is to test the logical function. Because those function will have side effect after you modify it.
If your getter and setter are just assign value and return value, there's no need to write your unit test.
Upvotes: 1
Reputation: 81
I personally wouldn't write any unit tests for setters and getters, unless your setters() and getters() contain some programmatic business logic i.e. something getting computed when the setter()/getter() are called.
For rest others methods the UT cases are must.
In some companies, the code coverage is very strict and to adhere to the process, we may have to write UT for getters() & setters() also. Although its not a bad idea to always write :-)
Upvotes: 0
Reputation: 751
i would at least write tests for
public void addItem(Scanable s){
scans.add(s);
}
@Override
public float getSum() {
int sum = 0;
for(Scanable x : this.scans){
sum+=x.getPrice();
}
return sum;
}
the reason is not primary to verify the current functionality, but more to be prepared for future changes. lets say, you decide at some point to not initialize the field scans
directly and have the possibility to run into a NPE, then your tests should expose this and you can react quite fast.
Upvotes: 1