【问题标题】:Junit error: Cannot make a static reference to the non static methodJunit 错误:无法对非静态方法进行静态引用
【发布时间】:2019-07-13 18:56:33
【问题描述】:
Mockito.when(ApiCallImpl.invokeSubmitApplicationForm(Mockito.anyString(),Mockito.any(AppFormDetails.class))).thenReturn(AppFormSubmissionBOResponse.class.getResource("/appFormSubmission_BO_Resp.json"));

当我尝试模拟第三方服务时,我遇到了错误。

Cannot make a static reference to the non static method invokeSubmitApplicationForm(String, AppFormDetails) from the type ApiCallImpl

【问题讨论】:

    标签: spring-boot junit


    【解决方案1】:

    invokeSubmitApplicationForm 是一个实例方法,所以它需要在一个实例上调用,或者,在这种情况下,是模拟实例:

    ApiCallImpl api = Mockito.mock(ApiCallImpl.class);
    Mockito.when(api.invokeSubmitApplicationForm
                      (Mockito.anyString(), Mockito.any(AppFormDetails.class))
                ).thenReturn(AppFormSubmissionBOResponse
                              .class
                              .getResource("/appFormSubmission_BO_Resp.json"));
    

    【讨论】:

    • 我试过这个。我收到此错误: OngoingStubbing 类型中的 thenReturn(AppFormSubmissionBOResponse) 方法不适用于争论(URL)。
    【解决方案2】:

    如果你正在使用 PowerMockito,请使用以下方法

    PowerMockito.mockStatic(StaticClass.class);
    PowerMockito.doReturn("WhatEverYouWant").when(StaticClass.class, "methodName", Mockito.anyString());
    

    如果使用 Mockito,则进行其他调整。

    别忘了在@PrepareForTest 部分中包含静态类。

    编辑:

    call = Mockito.mock(ApiCallImpl.class);
    Mockito.when(ApiCallImpl.invokeSubmitApplicationForm(Mockito.any(), Mockito.any()))
            .thenReturn(AppFormSubmissionBOResponse.class.getResource("/appFormSubmission_BO_Resp.json"));
    

    这就够了。

    private ApiCallImpl call; 
    

    应该是声明。

    【讨论】:

    • 但是我这里没有使用静态类。您能告诉我是否必须更改现有的非静态类吗?
    • 然后改成PowerMockito.mock(YourClass.class);
    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 2011-06-25
    • 2023-04-02
    • 2013-06-30
    相关资源
    最近更新 更多