官方文档: http://jmockit.github.io/tutorial/Mocking.html#singleInvocationCapture
学习:
https://bowenli86.github.io/2016/04/17/test/jmockit/Unit-Test-JMockit-Capturing-Invocation-Arguments-for-Verification/
官方文档翻译
Jmockit使用详解之Mocking
/**
* spring跨层mock,并且验证被mock的函数的值. 这个非常适合集成mock测试验证使用.
*
* @sina weibo regbin@tom.com
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:jdktest/jmockit/application-context.xml")
public class ServiceTest {
@Mocked
Remote remote;
@Autowired
Service service;
@Test
public void testDoFuncYes() {
service.doFunc(true, 3);
new Verifications() {
{
System.out.println("doSomething 1 begin");
//remote.doSomething(anyInt);//表示这个方法会被执行
ParameterBean bean = new ParameterBean(1);
remote.doSomething(bean = withCapture());
Assert.assertEquals(1, bean.num);
times = 1;//调用次数,0表示上面方法不会被调用
// 表示这个方法会被执行,而且参数是1;在当前case,会通过
//remote.doSomething(2);//表示这个方法会被执行,而且参数是2;在当前case,这个会不被通过
System.out.println("doSomething 1");
}
};
}
@org.springframework.stereotype.Service
private static class Remote {
public void doSomething(ParameterBean a) {
}
}
public static class ParameterBean {
public int num = 0;
public ParameterBean(int a) {
this.num = a;
}
}
@org.springframework.stereotype.Service
private static class Proxy {
@Autowired
Remote remote;
public void doFuncProxy(ParameterBean p) {
remote.doSomething(p);
}
}
@org.springframework.stereotype.Service
private static class Service {
@Autowired
private Proxy remote;
public void doFunc(boolean flag, int a) {
if (flag) {
remote.doFuncProxy(new ParameterBean(a));
}
}
}
}