【问题标题】:PowerMockito mockStatic gives MissingMethodInvocationExceptionPowerMockito mockStatic 给出 MissingMethodInvocationException
【发布时间】:2021-04-06 05:06:00
【问题描述】:

我正在尝试使用 PowerMockito 模拟静态方法,我尝试了一些选项来模拟一个类,导致不同的异常。

@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        when(Base64.getDecoder()).thenReturn(mockDecoder);

这导致org.mockito.exceptions.misusing.MissingMethodInvocationException:

我用了另一个这样的例子

@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        doReturn(mockDecoder).when(Base64.class, "getDecoder");

这给了我

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here: 

如果我使用

BDDMockito.given(Base64.getDecoder()).willReturn(mockDecoder);

Mocking static methods with Mockito ,它仍然返回 org.mockito.exceptions.misusing.MissingMethodInvocationException

我试图检查关于 SO 的类似问题,但它们似乎没有帮助。 任何解决此问题的帮助表示赞赏。

【问题讨论】:

    标签: powermockito


    【解决方案1】:

    我在此之后解决了它,所有其他解决方案都不适合我。很难找到这个解决方案,因为同一个 SO 上的太多了。

    PowerMockito mock single static method and return object inside another static method , PowerMock, mock a static method, THEN call real methods on all other statics

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({Base64.class})
    public class BqClientFactoryTest {
        @Test
        public void testGetBigQueryClient() throws Exception {
            Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
            stub(method(Base64.class, "getDecoder")).toReturn(mockDecoder);
    

    【讨论】:

    • 自从我现在找到了这个解决方案,不确定什么是正确的做法,因为它似乎是重复的。但是很难在这么多关于同一主题的问题和答案中找到。这个添加到它。
    猜你喜欢
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    相关资源
    最近更新 更多