将 PowerMock 与 Spock 结合使用 [英] Using PowerMock with Spock

查看:31
本文介绍了将 PowerMock 与 Spock 结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些静态方法的类.我需要模拟这些静态方法.我知道 PowerMock 会这样做,但是我找不到任何可以阐明Spock+PowerMock"集成的教程/材料.与 Junit 相比,我更喜欢 Spock,因此这是个难题.有没有办法让这两个框架发挥作用?非常感谢任何帮助.示例代码,更是如此.

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.

更新:该方法的现状

Spock 行为古怪

推荐答案

我也被困在这里一段时间了.搜索了几个小时后,我看到了这个 github 存储库:https://github.com/kriegaex/Spock_PowerMock.

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

我尝试添加一个 PowerMockRule,它基本上使我能够将 PowerMock 与 Spock 一起使用.我不得不添加这些依赖项.版本在 1.5.4

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>

我的班级是这样的:

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!"
    }
}

这是另一个资源:https://github.com/jayway/powermock/wiki/powermockrule

这篇关于将 PowerMock 与 Spock 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆