繁体   English   中英

在集成测试中使用PowerMock模拟Spring Boot静态方法

[英]Spring boot mocking static methods with PowerMock in Integration test

我正在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.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:org.powermock.core.MockRepository.addAfterMethodRunner(Ljava / lang / Runnable;) 50)

如果我取消注释@PowerMockRunnerDelegate(SpringRunner.class),则会出现此其他错误:

线程“主”中的异常java.lang.NoClassDefFoundError:org / powermock / core / testlisteners / GlobalNotificationBuildSupport $ Callback at 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);
    }
}

这是由于PowerMock和Mockito的库版本不兼容。 我建议检查PowerMock团队提供的兼容性版本表,或切换到JMockit以模拟静态和私有方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM