问题描述
我正在尝试使用EasyMock来模拟一些数据库接口,以便我可以通过包装方法测试业务逻辑。在我的测试设置中使用以下方法返回的方法一直很顺利。
I'm trying to use EasyMock to mock out some database interface so I can test the business logic off a wrapping method. I've been going ok with methods that return by using the following in my setup of my test.
DBMapper dbmapper = EasyMock.createMock(DBMapper.class);
userService.setDBMapper(dbmapper);
然后在我的实际测试中我运行
then within my actual test I run
EasyMock.expect(dbmapper.getUser(userId1)).andReturn(mockUser1);
EasyMock.replay(dbmapper);
userService.getUser(userId1);
此服务然后连接到dbmapper并返回对象(使用setter方法注入mapper)
This service then connects to the dbmapper and returns the object (the mapper is injected using setter methods)
这些类型的模拟似乎工作正常。但是,当我尝试运行测试
These type of mocks seem to work fine. However when I try to run a test for
userService.addUser(newUser1);
此方法调用void方法。
This method calls a void method.
dbmapper.createUser(newUser);
这种方法我遇到了嘲弄问题。
我试过以下
It's this method that I'm having problems mocking out.I've tried the following
EasyMock.expectLastCall();
EasyMock.replay(dbMapper);
userService.addUser(newUser1);
因为其他一些帖子/问题似乎暗示我得到 IlligalStateException:没有最后一个模拟可用
as some other posts/questions etc seem to suggest I get an IlligalStateException: no last call on a mock available
有人能指出我正确的方向吗?
Can anyone point me in the right direction please?
非常感谢提前
推荐答案
你已经离我很近了。
您只需在调用 expectLastCall()
所以你期望看起来像这样:
So you expectation would look like this:
userService.addUser(newUser1);
EasyMock.expectLastCall();
EasyMock.replay(dbMapper);
userService.addUser(newUser1);
这是因为模拟对象在调用重放之前处于记录模式()
,因此对它的任何调用都将执行默认行为(返回null /什么都不做),并且当 replay()
时有资格进行重放方法被调用。
This works because the mock object is in Record mode before the call to replay()
, so any calls to it will perform default behaviour (return null/do nothing) and will be eligible for replaying when the replay()
method is called.
我喜欢做什么来确保方法调用对于期望是显而易见的是在它前面放一个小注释像这样:
What I like to do to make sure that it is obvious the method call is for an expectation is to put a small comment in front of it like this:
/* expect */ userService.addUser(newUser1);
EasyMock.expectLastCall();
EasyMock.replay(dbMapper);
userService.addUser(newUser1);
这篇关于EasyMock void方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!