- 测试代码
public class BcdService {
public int add(int a, int b) {
return a + b;
}
}
- mock
@Test
public void testAdd() throws Exception {
BcdService bcdService = PowerMockito.mock(BcdService.class);
PowerMockito.whenNew(BcdService.class).withNoArguments().thenReturn(bcdService);
//PowerMockito.when(bcdService.add(1, 2)).thenReturn(5);
PowerMockito.doReturn(6).when(bcdService).add(1, 2);
System.out.println(bcdService.add(1, 2));
}
- spy 创建一个被监视的对象,对其行为进行监控修改
/**
* PowerMockito.spy mock目标对象的部分返回,实际可以调到真正的方法,只不过改变了方法的返回结果(改变部分实现)
* PowerMockito.mock mock调不到正真的方法,除非BcdService bcdService=new BcdService();
*/
@Test
public void testAddSpy() {
BcdService bcdService = PowerMockito.spy(new BcdService());
PowerMockito.when(bcdService.add(1, 2)).thenReturn(4);
System.out.println(bcdService.add(1, 2));
}
标签:基本,spy,PowerMockito,add,bcdService,PowerMock,BcdService,mock
From: https://blog.csdn.net/baidu_34848066/article/details/144962571