Java 将PowerMock与黄瓜一起使用
我已经编写了一个JUnit测试,它使用Mockito和PowerMock来模拟一些类。我试图将其转换为cumber测试,但静态PowerMock特性不起作用 两类相关黄瓜的提取物: 跑步者Java 将PowerMock与黄瓜一起使用,java,unit-testing,junit,cucumber,powermock,Java,Unit Testing,Junit,Cucumber,Powermock,我已经编写了一个JUnit测试,它使用Mockito和PowerMock来模拟一些类。我试图将其转换为cumber测试,但静态PowerMock特性不起作用 两类相关黄瓜的提取物: 跑步者 @RunWith(Cucumber.class) public class JWTValidatorBDDTest { } 步骤类 public class JWTValidatorCukeTest { String tokenValue; JWTValidator jwtValidator; MockHt
@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中工作?您不能使用
PowerMockRunner
,因为一个测试只能有一个运行程序(在您的情况下是Cucumber
)。但是,如果您可以使用而不是PowerMockRunner
,那么现在使用@powermockrunnerregate注释似乎是可能的。我使用了@RunWith(PowerMockRunner.class)和@powermockrunnerregate(Cucumber.class),它正在工作。从这里得到一个建议:
由于版本1.6.0,PowerMock支持将测试执行委托给另一个JUnit运行程序,而不使用JUnit规则。这将实际测试的执行留给您选择的另一个运行程序。例如,测试可以委托给“SpringJUnit4ClassRunner”、“参数化”或“封闭”运行程序
还有使用@Rule:PowerMockRule Rule=new PowerMockRule()的选项;而不是@RunWith(PowerMockRunner.class)(所以Runner可以是其他的东西)-但是Stefan Birkner的评论建议Cucumber Runner应该支持使用这个的规则,我不确定它是否支持(现在)
希望它对其他人有所帮助。我在这两个类中都添加了“@Rule\nPowerMockRule Rule=new PowerMockRule();”(同时在这两个类中都添加了“@PrepareForTest”),但输出没有更改。对不起,是我的错。Cucumber运行程序不支持规则。请尝试
@ClassRule PowerMockRule rule=new PowerMockRule()代码>。看起来Cucumber runner支持类规则。org.junit.internal.runnes.rules.ValidationError:@ClassRule“rule”必须实现TestRule
和org.junit.internal.runnes.rules.ValidationError:@ClassRule“rule”必须是静态的。
我一直在研究@ClassRule
的工作原理,但我找不到一个解决方案解决方案:-看来有人必须为Cucumber建立规则支持: