views:

500

answers:

2

I have the following code

Record rd = registerNewRecord();
<do some processing>
rd.setFinished(true);
updateRecord(rd);

The registerNewRecord method calls the RecordDao insert method, and updateRecord calls the update method on the same DAO.

I have the following easymock code:

Capture<Record> insertRc = new Capture<Record>();
RecordDao.insert(capture(insertRc));
Capture<Record> updateRc= new Capture<Record>();
RecordDao.update(capture(updateRc));

Problem is since above rd the same instance of Record that was inserted is being updated, the insertRc Capture object is being updated too. So i cannot assert that the finished flag is set to false at insert time.

What am i doing wrong?

A: 

One idea is to clone the Record object when you capture it.

Implement a clone() method in your Record class, and then implement a custom Capture as follows:

public class RecordCloneCapture extends Capture<Record> {
 @Override
 public void setValue(Record value) {
  super.setValue(value == null ? null : value.clone());
 }
}

And change your test code to use it:

Capture<Record> insertRc = new RecordCloneCapture();
RecordDao.insert(capture(insertRc));
Capture<Record> updateRc= new RecordCloneCapture();
RecordDao.update(capture(updateRc));

If you can't implement clone() for some reason, your custom Capture class could just extract the information it needs (i.e. the Record finished flag) in the setValue method and store it.

Joe Daley
A: 

If the references within insertRC and updateRC both refer to the same object rd and this is changed during the update method, you will always see that the Record object has finished. However, you could test the first Captured object before the update call is made.

Capture<Record> insertRc = new Capture<Record>();
RecordDao.insert(capture(insertRc));
Record insertedRecord = insertRC.getValue();
org.junit.Assert.assertFalse(insertedRecord.isFinished());

Capture<Record> updateRc= new Capture<Record>();
RecordDao.update(capture(updateRc));
Record updatedRecord = insertRC.getValue();
org.junit.Assert.assertTrue(updatedRecord.isFinished());
DoctorRuss