這裏第一次定時器,如果我錯過了任何事情,請致歉。 我希望能夠繞過使用Spock的靜態方法。反饋會很好使用GroovyMock或Spock中的類似方法模擬靜態方法
隨着groovy嘲笑,我想我能夠通過靜態調用,但還沒有找到它。 對於背景,我正在改造傳統java中的測試過程。重構是被禁止的。我用groovy-1.8使用spock-0.7。
的靜態方法的調用被鏈接在此形式的實例調用:
public class ClassUnderTest{
public void methodUnderTest(Parameter param){
//everything else commented out
Thing someThing = ClassWithStatic.staticMethodThatReturnsAnInstance().instanceMethod(param);
}
}
STATICMETHOD返回ClassWithStatic instanceMethod的實例返回該方法的其餘部分所需要的東西
如果我直接運行全局模擬,它返回模擬實例ok:
def exerciseTheStaticMock(){
given:
def globalMock = GroovyMock(ClassWithStatic,global: true)
def instanceMock = Mock(ClassWithStatic)
when:
println(ClassWithStatic.staticMethodThatReturnsAnInstance().instanceMethod(testParam))
then:
interaction{
1 * ClassWithStatic.staticMethodThatReturnsAnInstance() >> instanceMock
1 * instanceMock.instanceMethod(_) >> returnThing
}
}
但是如果我運行方法dUnderTest從ClassUnderTest:
def failingAttemptToGetPastStatic(){
given:
def globalMock = GroovyMock(ClassWithStatic,global: true)
def instanceMock = Mock(ClassWithStatic)
ClassUnderTest myClassUnderTest = new ClassUnderTest()
when:
myClassUnderTest.methodUnderTest(testParam)
then:
interaction{
1 * ClassWithStatic.staticMethodThatReturnsAnInstance() >> instanceMock
1 * instanceMock.instanceMethod(_) >> returnThing
}
}
它摔倒ClassWithStatic的一個真正的實例繼續在其instanceMethod失敗。
如果幫助某人,我在Spock中使用GroovyMock來更改Java代碼中的靜態方法,但是這會錯誤地影響其他測試。我用這個註釋來解決問題@ConfineMetaClassChanges – Topera 2016-10-14 00:49:25