[英]How do I mock a method using EasyMock
User getUser(int id) {
User user = service.get( id );
if( user != null ) {
user.Stuff = getUserStuff( id );
return User;
}
throw new NotFoundException();
}
Stuff getUserStuff( int id ) {
stuffGetter.getStuff( id ); // stuff getter makes a rest call
return Stuff;
}
使用EasyMock,我将如何测试getUser(id)
方法。 对我来说,令人困惑的部分是getUserStuff(id)
进行了外部调用,而我在测试getUser
时不想进行此调用。
正如其他用户在评论中提到的那样,您需要提供正在进行您希望模拟的调用的对象的模拟实例。
因此,在getUser(id)
我可以看到对名为service
的对象的调用,该调用应被模拟出来。 因此,使用服务类的模拟实例,然后可以模拟对get(id)
的调用。
然后,在getUserstuff(id)
方法中,它使用了stuffGetter
对象,该对象可以再次被stuffGetter
出来。 然后,被调用的方法可能会为此设置期望。 ( 对此的一种替代方法也可以是设置部分模拟并一起模拟getUSerstuff(id)
方法,但这超出了我想做的工作 )
考虑到这些因素,我创建了以下类来测试您描述的用例:
public class ClassToTest {
private final Service service;
private final StuffGetter stuffGetter;
public ClassToTest() {
this( new Service(), new StuffGetter() );
}
public ClassToTest(final Service service, final StuffGetter stuffGetter) {
this.service = service;
this.stuffGetter = stuffGetter;
}
public User getUser(final int id) {
final User user = this.service.get( id );
if( user != null ) {
user.stuff = getUserStuff( id );
return user;
}
throw new NotFoundException();
}
public Stuff getUserStuff( final int id ) {
return this.stuffGetter.getStuff( id );
}
}
像这样设置构造函数使我能够在测试中设置依赖项的模拟实例。 因此,下面是对getUser(id)
方法的测试,该方法对两个对象使用了模拟。 它使用基本EasyMock概念进行期望,重播和验证。
service
和stuffGetter
。 expect
方法编写方法调用的expect
。 在此处指定如果您模拟的方法不是void方法将返回的内容。 测试看起来像这样:
import static org.junit.Assert.assertEquals;
import org.easymock.EasyMock;
import org.junit.Test;
public class ClassToTestTest {
@Test
public void thatGetIdCallsExpectedMockMethods() {
final User user = new User();
final Stuff userStuff = new Stuff();
final Service mockService = EasyMock.createMock(Service.class);
final StuffGetter mockStuffGetter = EasyMock.createMock(StuffGetter.class);
EasyMock.expect( mockService.get(15) ).andReturn( user );
EasyMock.expect( mockStuffGetter.getStuff(15) ).andReturn( userStuff );
EasyMock.replay( mockService, mockStuffGetter );
final ClassToTest classToTest = new ClassToTest( mockService, mockStuffGetter );
final User returnedUser = classToTest.getUser(15);
assertEquals(returnedUser, user);
assertEquals(returnedUser.stuff, userStuff);
EasyMock.verify( mockService, mockStuffGetter );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.