Mock static method with GroovyMock or similar in Spock

前端 未结 3 1658
误落风尘
误落风尘 2020-12-10 12:07

First-timer here, apologies if I\'ve missed anything. I\'m hoping to get around a call to a static method using Spock. Feedback would be great

With groovy mocks, I

3条回答
  •  天涯浪人
    2020-12-10 12:55

    Here is how I solved my similar issue (mocking a static method call which is being called from another static class) with Spock (v1.0) and PowerMock (v1.6.4)

    import org.junit.Rule
    import org.powermock.core.classloader.annotations.PowerMockIgnore
    import org.powermock.core.classloader.annotations.PrepareForTest
    import org.powermock.modules.junit4.rule.PowerMockRule
    import spock.lang.Specification
    import static org.powermock.api.mockito.PowerMockito.mockStatic
    import static org.powermock.api.mockito.PowerMockito.when
    
    @PrepareForTest([YourStaticClass.class])
    @PowerMockIgnore(["javax.xml.*", "ch.qos.logback.*", "org.slf4j.*"])
    class YourSpockSpec extends Specification {
    
    @Rule
    Powermocked powermocked = new Powermocked();
    
    def "something something something something"() {
        mockStatic(YourStaticClass.class)
    
        when: 'something something'
        def mocked = Mock(YourClass)
        mocked.someMethod(_) >> "return me"
    
        when(YourStaticClass.someStaticMethod(xyz)).thenReturn(mocked)
    
        then: 'expect something'
        YourStaticClass.someStaticMethod(xyz).someMethod(abc) == "return me"
    
       }
    }
    

    The @PowerMockIgnore annotation is optional, only use it if there is some conflicts with existing libraries

提交回复
热议问题