I’ve been banging my head against the wall for a while with this one –
I have a method to create a list of objects of another class:
public List <PayrollRecord> processPayroll() {
List<PayrollRecord> payroll = new ArrayList<PayrollRecord>();
for (Employee employee : staff) {
PayrollRecord payRec = new PayrollRecord(employee.getName(), employee.calculatePay());
payroll.add(payRec);
}
return payroll;
}
staff is a list of Employee class objects that can be added to the list by this method:
public void addEmployee(Employee employee) {
staff.add(employee);
}
Employee is also an interface implemented by a few other classes – Manager, SalesAssociate and StoreEmployee. (Can you tell I’m trying to get through an assignment yet? Maybe some of you are familiar).
The PayrollRecord class looks like this:
package my.package.ext;
public class PayrollRecord {
private String employeeName;
private double currentPay;
public PayrollRecord(String employeeName, double currentPay) {
}
public double getCurrentPay() {
return this.currentPay;
}
public String getEmployeeName() {
return this.employeeName;
}
}
So within a test class, I should be able to create some variables for employee info, add some employees to staff, and then run the processPayroll method and do some asserts on it. My test class currently looks like this (and will need several more asserts. I’m not going to bother adding those until I can get this basic problem figured out):
@Test
public void testPayroll() {
List<PayrollRecord> list = store.processPayroll();
assertEquals(managerTestPay, list.get(0).getCurrentPay(), 0);
}
Based on the number of employees I have added elsewhere in the test class, there should be five. I can set list.get out of bounds and verify that there are indeed 5. However the problem is that all 5 records are null and 0.0. I should have a name and pay for each employee record. However the assertion error comes back showing me what I expected, but that the actual value is 0.0 (or null when I try list.get(0).getName()).
Thank you in advance for your help and wisdom.
And you set the members how ?
In your constructor you need to assign to the members e.g.
It’s not enough to simply call the constructor with arguments. The arguments need to be used to populate the members of the class (either directly or via some manipulation).
A useful technique here is to set the member variables to be
final. This means:You might think this is a limitation. However a lot of the time you’ll find you only set this info once (I suspect for your assignment the name and salary will remain constant). If you need to change one or other it’s easy to remove the
finalqualification.Ensuring that the members don’t change means the class instance is immutable. This is a good thing generally. It’s easy to reason about and debug immutable classes, and they’re implicitly thread-safe.