我正在 SpringBoot 中的 RestController 上编写集成测试。 通常我会使用 SpringRunner.class 运行,但是当涉及到 Mock 静态方法时,我需要使用 PowerMock。
奇怪的事实是,当我运行单个测试时,它们单独通过(但返回错误消息),当我尝试运行整个测试类时,没有测试通过并且返回相同的错误消息。
@RunWith(PowerMockRunner.class)
@PrepareForTest({JwtUtils.class})
//@PowerMockRunnerDelegate(SpringRunner.class) THIS DOESN'T WORK!!!
@SpringBootTest(classes = SpringBootJwtApplication.class)
public class RestAccessIntegrationTest {
@Autowired @InjectMocks
RestController restController;
@Mock
HttpServletRequest request;
@Test
public void operationsPerAccountWhenSuccessfulTest(){
mockStatic(JwtUtils.class);
when(JwtUtils.myMethod(request)).thenReturn("blabla");
String expected = ... ;
String actual = restController.getOperations();
assertEquals(actual, expected);
}
}
如果我运行测试或整个类,我会收到此类错误:
线程“main”中出现异常 java.lang.NoSuchMethodError: org.powermock.core.MockRepository.addAfterMethodRunner(Ljava/lang/Runnable;)at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator .java:50)
如果我取消注释@PowerMockRunnerDelegate(SpringRunner.class),则会出现另一个错误:
线程“main”中出现异常 java.lang.NoClassDefFoundError: org/powermock/core/teSTListeners/GlobalNotificationBuildSupport$Callback 在 org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:139)
最佳答案
在 when
方法中,尝试使用 any(HttpServletRequest.class)
而不是 request
模拟对象。还可以使用 MockHttpServletRequest
而不是模拟 HttpServletRequest
。这应该有效,
@RunWith(PowerMockRunner.class)
@PrepareForTest(JwtUtils.class)
@PowerMockIgnore( {"javax.management.*"})
public class RestAccessIntegrationTest {
@InjectMocks
private RestController restController;
private MockHttpServletRequest request;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(
new ServletRequestAttributes(request));
}
@Test
public void operationsPerAccountWhenSuccessfulTest() {
mockStatic(JwtUtils.class);
when(JwtUtils.myMethod(any(HttpServletRequest.class)))
.thenReturn("blabla");
String expected = ... ;
// does your getOperations take HttpServletRequest
// as parameter, then controller.getOperations(request);
String actual = restController.getOperations();
assertEquals(actual, expected);
}
}
关于unit-testing - Spring Boot 在集成测试中使用 PowerMock 模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610835/