本文共 1953 字,大约阅读时间需要 6 分钟。
easymock使用方法
Sometimes we want to mock void methods. EasyMock expect()
method can’t be used to mock void methods. However, we can use expectLastCall()
along with andAnswer()
to mock void methods.
有时我们想模拟void方法。 EasyMock Expect expect()
方法不能用于模拟void方法。 但是,我们可以使用expectLastCall()
连同andAnswer()
嘲笑无效的方法。
When we use expectLastCall()
and andAnswer()
to mock void methods, we can use getCurrentArguments()
to get the arguments passed to the method and perform some action on it. Finally, we have to return null since we are mocking a void method.
当我们使用andAnswer()
expectLastCall()
和andAnswer()
来模拟void方法时,可以使用getCurrentArguments()
来获取传递给该方法的参数并对其执行一些操作。 最后,由于要模拟void方法,因此必须返回null 。
Let’s say we have a utility class as:
假设我们有一个实用程序类:
package com.journaldev.utils;public class StringUtils { public void print(String s) { System.out.println(s); }}
Here is the code to mock void method print() using EasyMock.
这是使用EasyMock模拟void方法print()的代码。
package com.journaldev.easymock;import static org.easymock.EasyMock.*;import org.junit.jupiter.api.Test;import com.journaldev.utils.StringUtils;public class EasyMockVoidMethodExample { @Test public void test() { StringUtils mock = mock(StringUtils.class); mock.print(anyString()); expectLastCall().andAnswer(() -> { System.out.println("Mock Argument = " +getCurrentArguments()[0]); return null; }).times(2); replay(mock); mock.print("Java"); mock.print("Python"); verify(mock); }}
Below image shows the console output when the above test is executed.
下图显示了执行上述测试时的控制台输出。
If we just want to mock void method and don’t want to perform any logic, we can simply use expectLastCall().andVoid()
right after calling void method on mocked object.
如果我们只想模拟void方法并且不想执行任何逻辑,则可以在对模拟对象调用void方法之后expectLastCall().andVoid()
使用expectLastCall().andVoid()
。
翻译自:
easymock使用方法
转载地址:http://hxmzd.baihongyu.com/