How to test with easymock capture

I have the following code

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

The registerNewRecord method calls the RecordDao insertion method, and updateRecord calls the update method in 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));

The problem is that above rd the same Record instance that was inserted is updated, the InsertRc Capture object is also updated. Therefore, I cannot claim that the set flag is set to false during insertion.

What am I doing wrong?

+3
source share
3 answers

insertRC updateRC rd, update, , Record . , Captured update.

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 = updateRC.getValue();
org.junit.Assert.assertTrue(updatedRecord.isFinished());
+3

- Record .

clone() , Capture :

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

, :

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

clone() - , Capture ( ) setValue .

+1

- . , registerNewRecord (, ). , new, . , / , .

, registerNewRecord() , , Record. Record - registerNewRecord() . , Record, .

MyClassStub extends MyClass {
  Record registerNewRecord() {
    return recordMock;
  }
}

MyClass objectToTest = new MyClassStub();

public void testSomeMethod() {
   // set expectations, call replay
   objectToTest.someMethod();  // (contains above code that calls registerRecord)
   // asserts/verify
}

As a positive side effect, you will find that your test only breaks when something is wrong with the code in the method you are testing, and never breaks if the problem is with the write constructor or registerNewRecord. However, you will want to write a second test for the method registerNewRecord()to make sure that it works correctly.

0
source

Source: https://habr.com/ru/post/1724380/


All Articles