V Ng
V Ng

Reputation: 41

How to get input argument from a mock method using PowerMock / EasyMock

I have a entity Person class. A ProcessPerson class which contain process() method needs to be tested.

What I need is to get the object is created in the process() method and is called via mock method create() of mock object personDao.

public class Person { 
    private String firstName;
    private String lastName;

      public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

public class ProcessPerson {
    @Autowired
    private PersonDao personDao;

    public void process() {
        Person person1 = new Person();
        person1.setFirstName("FN");
        //Do more logic to fill values into person object


        personDao.create(person1);
    }
}

import static org.powermock.api.easymock.PowerMock.*;
import static org.easymock.EasyMock.expect;

@RunWith(PowerMockRunner.class)
@PrepareForTest ( {Person.class} )
public class TestClass {

    @Test
    public void TestCase1() {
        ProcessPerson process = new ProcessPerson();

        //Create dependent DAO mock object
        PersonDao personDaoMock = createMock(PersonDao.class);

        //Inject mock object
        ReflectionTestUtils.setField(process, "personDao", personDaoMock);

        replayAll();

        process.process();

        //QUESTION here: can I get the object person1 which was created in process() method 
        //and called via create() function of my mock object
        //
        //I need the object to do verification like this
        //Assert.assertEqual(person1.getFirstName(), "FN");

        verifyAll();
    }
}

Any suggestion, idea is welcome

Thanks

Upvotes: 3

Views: 4259

Answers (1)

centic
centic

Reputation: 15882

EasyMock has "andDelegateTo", which can be used for what you would like to do. It allows you to get some local code called when the mock is called. I use the AtomicReference to get the person object from the anonymous inner class.

@Test
public void TestCase1() {
    ProcessPerson process = new ProcessPerson();

    //Create dependent DAO mock object
    PersonDao personDaoMock = createMock(PersonDao.class);

    //Inject mock object
    ReflectionTestUtils.setField(process, "personDao", personDaoMock);

    final AtomicReference<Person> ref = new AtomicReference<Person>();

    personDaoMock.create(anyPerson());
    //expectLastCall().andDelegateTo(null);
    expectLastCall().andDelegateTo(new PersonDao() {
            @Override
            public void create(Person person1) {
                ref.set(person1);
            }
    });

    replayAll();

    process.process();

    assertNotNull(ref.get());

    verifyAll();
}

public static Person anyPerson()
{
    reportMatcher(Any.ANY);
    return null;
}

See the EasyMock Documentation for some more details on andDelegateTo().

Upvotes: 1

Related Questions