Using PowerMock with Spock

Avinash picture Avinash · Oct 21, 2013 · Viewed 8.8k times · Source

I have a class with a few static methods.I need to Mock these static methods. I know PowerMock does this,but I was not able to find any tutorials/materials that shed some light on "Spock+PowerMock" integration. I prefer Spock to Junit,hence the conundrum. Is there a way of getting these 2 frameworks to play ball?Any help is much appreciated.Sample code,even more so.

Update: Current Status of the Approach

Spock behaving weirdly

Answer

juanpaolo picture juanpaolo · Jul 15, 2014

I was stuck here for a while too. After searching for hours, I saw this github repo: https://github.com/kriegaex/Spock_PowerMock.

I tried adding a PowerMockRule which essentially enabled me to use PowerMock together with Spock. I had to add these dependencies. Version is at 1.5.4

   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>

   <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-rule</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-classloading-xstream</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>

My class looks like this:

import org.junit.Rule
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.rule.PowerMockRule
import spock.lang.Specification

@PrepareForTest([SomeStaticClass.class])
public class FlightFormSpec extends Specification { 

    @Rule PowerMockRule powerMockRule = new PowerMockRule();

    def "When mocking static"() {
        setup :
            PowerMockito.mockStatic(SomeStaticClass.class)

        when :
            Mockito.when(SomeStaticClass.someStaticMethod()).thenReturn("Philippines!");

        then :
            SomeStaticClass.someStaticMethod() == "Philippines!"
    }
}

Here is another resource: https://github.com/jayway/powermock/wiki/powermockrule