我有一个实体Person类。 需要测试包含process()方法的ProcessPerson类。
我需要的是在process()方法中创建对象,并通过模拟对象personDao的mock方法调用。
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();
}
}
任何建议,欢迎提出想法
由于
答案 0 :(得分:1)
EasyMock有“andDelegateTo”,可以用于你想做的事情。它允许您在调用mock时调用一些本地代码。我使用AtomicReference从匿名内部类中获取person对象。
@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 Documentation。