打桩类的私有变量
ReflectionTestUtils.setField(xxxService, "field", "value");
在@InjectMocks对象的fields里面,使用@InjectMocks对象
// AService.java
public class AService {
@Autowired
private BSerivce bSerivce;
@Autowired
private CService cSerivce;
}
// Test.java
...
public class Test {
@Mock
private BSerivce bSerivce;
@InjectMocks
ASerivce aSerivce = new AService();
@InjectMocks
CService cService = new CService();
@Before
public void before() {
ReflectionTestUtils.setField(AService, "cService", cService);
}
// do test
}
Method method = XXXClass.class.getDeclaredMethod("methodName", Param.class);
method.setAccessible(true);
Object result = method.invoke(XXXClassInstance, param);
使用
PowerMock
和@spy
可以打桩私有方法
个人体会:在@spy
对象里面打桩私有方法没什么实际用处,原因见下一条
@RunWith(PowerMockRunner.class)
@PrepareForTest(XXService.class)
@PowerMockIgnore(value = {"javax.net.ssl.*", "javax.management.*"})
public class XXServiceTest {
// ...
@Test
public void test(){
XXSerivce spy = PowerMockito.spy(new XXSerivce());
when(spy, method(XXSerivce.class, "dosomething", Param1.class, Param2.class))
.withArguments(any(), any())
.thenReturn(new Object());
}
}
起因:测试
InjectMocks
的Service的A方法,A方法调用了一个逻辑复杂的private B方法,想直接打桩这个方法。
调查结果:无法在InjectMocks
对象里面打桩私有方法
https://www.baeldung.com/mockito-annotations
测试方法抛出的异常
try {
this.XXService.doSomething(param, Lists.newArrayList());
fail();
} catch (Exception e) {
Assert.assertEquals(expect, actual);
}
网友评论