I've written a JUnit test that uses Mockito and PowerMock to mock some classes. I'm trying to convert it a Cucumber test, but the static PowerMock features don't work.
Extracts of the two relevant Cucumber classes:
Runner
@RunWith(Cucumber.class)
public class JWTValidatorBDDTest {
}
Steps Class
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;
}
Whilst this code works within the JUnit test, it fails here - it enters the JWTAuthConnectionManager.postToken()
method that should be mocked and then fails by executing code within there. I've tried adding the lines:
@RunWith(PowerMockRunner.class)
@PrepareForTest(JWTAuthConnectionManager.class)
to both of the above classes (although of course I can't use RunWith
in the Runner
class as it already has one RunWith
annotation), but this doesn't change anything.
How do I get PowerMock to work within Cucumber?
Seems like it is possible now with @PowerMockRunnerDelegate annotation. I use @RunWith(PowerMockRunner.class) and @PowerMockRunnerDelegate(Cucumber.class) and it's working. Taken an advise from here: https://medium.com/@WZNote/how-to-make-spock-and-powermock-work-together-a1889e9c5692
Since version 1.6.0 PowerMock has support for delegating the test execution to another JUnit runner without using a JUnit Rule. This leaves the actual test-execution to another runner of your choice. For example tests can delegate to “SpringJUnit4ClassRunner”, “Parameterized” or the “Enclosed” runner.
There are also options of using @Rule: PowerMockRule rule = new PowerMockRule(); instead of @RunWith(PowerMockRunner.class) (so Runner can be something else) - but the comment by Stefan Birkner suggests that Cucumber runner should support rules to use this and I am not sure if it does (now).
Hope it helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With