Search code examples
javajunitspring-batch

UnitTest a SpringBatch FieldSetMapper


I got the following custom FieldSetMapper

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

import de.BasicProperty;

public class PersonItemFieldSetMapper implements FieldSetMapper<PersonItem> {

    @Override
    public PersonItem mapFieldSet(final FieldSet fieldSet) throws BindException {
        PersonItem person = new PersonItem();
        person.setLastName(fieldSet.readString(BasicProperty.BASICPROP_LASTNAME));
        person.setFirstName(fieldSet.readString(BasicProperty.BASICPROP_FIRSTNAME));
        person.setEmployeeType(fieldSet.readString("EmployeeType"));
        person.setFormOfAdress(fieldSet.readString(BasicProperty.BASICPROP_FORMOFADDRESS));
        person.setEMail(fieldSet.readString(BasicProperty.BASICPROP_EMAIL));
        person.setUpn(fieldSet.readString(BasicProperty.BASICPROP_UPN));
        person.setWorkforceId(fieldSet.readString(BasicProperty.BASICPROP_WORKFORCE_ID));
        person.setInstitute(fieldSet.readString(BasicProperty.BASICPROP_INSTITUTE));
        person.setPhoto(fieldSet.readString(BasicProperty.BASICPROP_PHOTO));

        return person;
    }

}

At the moment i am trying to write a unit-test for this mapper. First Question: Is this reasonable? Second Question: How can i achieve this?


Solution

  • Yes you can write Test Cases for mapFieldSet()

    You can always write such test cases to make sure your mapping are good!
    // Using EasyMock to mock FieldSet  
    @Test
    public void mapFieldSetTest()
    {
        FieldSet mockFieldSet = EasyMock.createMock(FieldSet.class);
    
        EasyMock.expect(mockFieldSet.readString("LNAME")).andReturn("Doe");
        EasyMock.expect(mockFieldSet.readString("FNAME")).andReturn("John");
        EasyMock.expect(mockFieldSet.readString("ETYPE")).andReturn("PART-TIME");
        EasyMock.expect(mockFieldSet.readString("FADDRESS")).andReturn("191, Santa Clara");
        EasyMock.expect(mockFieldSet.readString("EMAIL")).andReturn("[email protected]");
        EasyMock.expect(mockFieldSet.readString("UPN")).andReturn("1111111111");
        EasyMock.expect(mockFieldSet.readString("WFID")).andReturn("22222222");
        EasyMock.expect(mockFieldSet.readString("INS")).andReturn("CA University College");
        EasyMock.expect(mockFieldSet.readString("PIC")).andReturn("c:\\john_doe.jpg");
    
        EasyMock.replay(mockFieldSet);
    
        // call the method under test
        PersonItem actual = fieldSetMapper.mapFieldSet(mockFieldSet);
    
        EasyMock.verify(mockFieldSet);
    
        // assert actual data by getters..
    }