代码之家  ›  专栏  ›  技术社区  ›  Alessandro Argentieri

集成测试中使用PowerMock的Spring引导模拟静态方法

  •  2
  • Alessandro Argentieri  · 技术社区  · 7 年前

    我正在SpringBoot中的RestController上编写集成测试。 通常我会和SpringRunner一起跑步。类,但在模拟静态方法时,我需要使用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。果心MockRepository。addAfterMethodRunner(Ljava/lang/Runnable;)在org。powermock。应用程序编程接口。莫基托。内部的模拟创建。MockCreator。mock(MockCreator.java:50)

    如果我取消注释@powermockrunnerregate(SpringRunner.class),则会出现另一个错误:

    线程“main”java中出现异常。lang.NoClassDefFoundError:org/powermock/core/testlisteners/GlobalNotificationBuildSupport$Callback 在org。powermock。模块。junit4.internal。impl。DelegatingPowerMockRunner。运行(DelegatingPowerMockRunner.java:139)

    2 回复  |  直到 7 年前
        1
  •  2
  •   Indra Basak    7 年前

    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);
        }
    }
    
        2
  •  1
  •   Alessandro Argentieri    7 年前