【问题标题】:Using PowerMock with Cucumber将 PowerMock 与 Cucumber 一起使用
【发布时间】:2015-12-01 17:11:38
【问题描述】:

我编写了一个 JUnit 测试,它使用 Mockito 和 PowerMock 来模拟一些类。我正在尝试将其转换为 Cucumber 测试,但静态 PowerMock 功能不起作用。

两个相关 Cucumber 类的摘录:

跑步者

@RunWith(Cucumber.class)
public class JWTValidatorBDDTest {
}

步骤类

public class JWTValidatorCukeTest {
String tokenValue;
JWTValidator jwtValidator;
MockHttpServletRequest mockRequest;

@Before
public void before() throws IOException {
    this.mockRequest = new MockHttpServletRequest();
    PowerMockito.mockStatic(JWTAuthConnectionManager.class);
    BDDMockito.given(JWTAuthConnectionManager.postToken(anyString(), anyString(), anyString())).willReturn(200);
    Mockito.doReturn(200).when(JWTAuthConnectionManager.postToken(anyString(), anyString(), anyString()));
}

@Given("^a JWT token with the value (.*)")
public void a_JWT_token_with_the_value_(String token) {
    this.jwtValidator = new JWTValidator("https://test.7uj67hgfh.com/openam", "Authorization", "Bearer");
    this.tokenValue = token;
}

虽然此代码在 JUnit 测试中有效,但在此处失败 - 它进入应该模拟的 JWTAuthConnectionManager.postToken() 方法,然后通过在其中执行代码而失败。我试过添加这些行:

@RunWith(PowerMockRunner.class)
@PrepareForTest(JWTAuthConnectionManager.class)

对上述两个类(当然我不能在Runner 类中使用RunWith,因为它已经有一个RunWith 注释),但这并没有改变任何东西。

如何让 PowerMock 在 Cucumber 中工作?

【问题讨论】:

    标签: java unit-testing junit cucumber powermock


    【解决方案1】:

    现在似乎可以使用 @PowerMockRunnerDelegate 注释。我使用 @RunWith(PowerMockRunner.class) 和 @PowerMockRunnerDelegate(Cucumber.class) 并且它正在工作。从这里获得建议:https://medium.com/@WZNote/how-to-make-spock-and-powermock-work-together-a1889e9c5692

    从 1.6.0 版开始,PowerMock 支持在不使用 JUnit 规则的情况下将测试执行委托给另一个 JUnit 运行器。这会将实际的测试执行留给您选择的另一个跑步者。例如,测试可以委托给“SpringJUnit4ClassRunner”、“Parameterized”或“Enclosed”运行器。

    还有使用@Rule 的选项: PowerMockRule rule = new PowerMockRule();而不是 @RunWith(PowerMockRunner.class) (所以 Runner 可以是别的东西) - 但 Stefan Birkner 的评论表明 Cucumber runner 应该支持使用它的规则,我不确定它是否(现在)。

    希望对某人有所帮助。

    【讨论】:

      【解决方案2】:

      您不能使用PowerMockRunner,因为测试只能有一个运行器(在您的情况下为Cucumber)。但是 AFAIK 你可以使用PowerMockRule 而不是PowerMockRunner

      【讨论】:

      • 我添加了“@Rule\nPowerMockRule rule = new PowerMockRule();”进入两个类(同时在两者中添加“@PrepareForTest”),而不改变输出。
      • 对不起,我的错。 Cucumber runner 不支持规则。
      • 你可以试试@ClassRule PowerMockRule rule = new PowerMockRule();。看起来 Cucumber runner 正在支持 ClassRules。
      • org.junit.internal.runners.rules.ValidationError: The @ClassRule 'rule' must implement TestRuleorg.junit.internal.runnes.rules.ValidationError: The @ClassRule 'rule' must be static. 我一直在研究 @ClassRule 的工作原理,但找不到解决方案。
      • :-( 看起来有人必须为 Cucumber 构建规则支持:github.com/cucumber/cucumber-jvm/issues/894
      猜你喜欢
      • 1970-01-01
      • 2022-06-10
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      相关资源
      最近更新 更多