public class ToBeTested{
public void myMethodToTest(){
...
String s = makeStaticWrappedCall();
...
}
String makeStaticWrappedCall(){
return Util.staticMethodCall();
}
}
2) 在测试和模拟包装包级方法时监视被测类:
public class ToBeTestedTest{
@Spy
ToBeTested tbTestedSpy = new ToBeTested();
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void myMethodToTestTest() throws Exception{
// Arrange
doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall();
// Act
tbTestedSpy.myMethodToTest();
}
}
(虽然我假设你可以使用 Mockito)我没有想到什么专门的,但在遇到这种情况时,我倾向于使用以下策略:
1) 在被测类中,将静态直接调用替换为对包装静态调用本身的包级方法的调用:
2) 在测试和模拟包装包级方法时监视被测类:
这是我写的一篇关于间谍的文章,其中包含类似的案例,如果您需要更多见解: sourceartists.com/mockito-spying