3

我有一个实体 Person 类。需要测试包含 process() 方法的 ProcessPerson 类。

我需要的是在 process() 方法中创建对象,并通过模拟对象 personDao 的模拟方法 create() 调用。

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();
    }
}

欢迎任何建议,想法

谢谢

4

1 回答 1

1

EasyMock 有“andDelegateTo”,可以用来做你想做的事。它允许您在调用模拟时调用一些本地代码。我使用 AtomicReference 从匿名内部类中获取人员对象。

@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;
}

有关andDelegateTo() 的更多详细信息,请参阅EasyMock 文档。

于 2012-03-03T20:18:14.200 回答