問題描述
在 JUnit 中進行測試時,有什么方法可以模擬靜態 util 方法嗎?
Is there any way we can mock the static util method while testing in JUnit?
我知道 Powermock 可以模擬靜態調用,但我不想使用 Powermock.
I know Powermock can mock static calls, but I don't want to use Powermock.
還有其他選擇嗎?
推薦答案
(不過我假設你可以使用 Mockito)我沒有想到任何專門的東西,但是當涉及到這樣的情況時,我傾向于使用以下策略:
(I assume you can use Mockito though) Nothing dedicated comes to my mind but I tend to use the following strategy when it comes to situations like that:
1) 在被測類中,將靜態直接調用替換為對封裝靜態調用本身的包級方法的調用:
1) In the class under test, replace the static direct call with a call to a package level method that wraps the static call itself:
public class ToBeTested{
public void myMethodToTest(){
...
String s = makeStaticWrappedCall();
...
}
String makeStaticWrappedCall(){
return Util.staticMethodCall();
}
}
2) 在測試和模擬封裝的包級方法時監視被測類:
2) Spy the class under test while testing and mock the wrapped package level method:
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();
}
}
這是我寫的一篇關于間諜的文章,其中包括類似的案例,如果您需要更多見解:sourceartists.com/mockito-spying
Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists.com/mockito-spying
這篇關于如何在沒有 powermock 的情況下模擬靜態方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!