Unit testing 集成测试中使用PowerMock的Spring引导模拟静态方法
我正在SpringBoot中的RestController上编写集成测试。 通常我会使用SpringRunner.class运行,但当涉及到模拟静态方法时,我需要使用PowerMock 奇怪的是,当我运行单个测试时,它们分别通过(但返回错误消息),当我尝试运行整个测试类时,没有测试通过,它返回相同的错误消息Unit testing 集成测试中使用PowerMock的Spring引导模拟静态方法,unit-testing,spring-boot,junit,mockito,powermock,Unit Testing,Spring Boot,Junit,Mockito,Powermock,我正在SpringBoot中的RestController上编写集成测试。 通常我会使用SpringRunner.class运行,但当涉及到模拟静态方法时,我需要使用PowerMock 奇怪的是,当我运行单个测试时,它们分别通过(但返回错误消息),当我尝试运行整个测试类时,没有测试通过,它返回相同的错误消息 @RunWith(PowerMockRunner.class) @PrepareForTest({JwtUtils.class}) //@PowerMockRunnerDelegate(Sp
@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;)中的异常位于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)
而不是请求
模拟对象。也可以使用MockHttpServletRequest
代替mockingHttpServletRequest
。这应该行得通
@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);
}
}
这是因为PowerMock和Mockito的库版本不兼容。我建议检查PowerMock团队提供的兼容性版本表,或者切换到JMockit以模拟静态和私有方法。您是否仍在使用
@SpringBootTest(classes=SpringBootJwtApplication.class)
?当我不使用它时,我没有得到任何异常。我试过使用和不使用。。。我已经使用了你给我的所有指示。奇怪的是,每一个测试都有效,而整个类却不行。