模拟使用Mockito在最后一堂课内的方法

发布于 2025-02-07 05:31:50 字数 920 浏览 0 评论 0原文

我需要在ViewModeltest中模拟状态代码

public final class PolicySummaryUtils {
   public PolicySummaryResponse.Policy getPolicy() {
       return getPolicySummaryResponse().accounts.get(0).policies.get(0);
   }
}

 public static class Policy {
    @Expose
    public String sCode;
    @SerializedName("policySource")
}

。有可能嘲笑这个吗?我嘲笑了策略,SCODE返回为null

@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class ViewModelTest{

    @Mock
    lateinit var summaryUtils: PolicySummaryUtils

    @Mock
    lateinit var policy: Policy

    @Test
    fun payBill_return_acceptedPayBillResponse(){
        return runTest {
            Mockito.when(summaryUtils.policyNumber).thenReturn(MOCK_POLICY_NO)
            Mockito.when(summaryUtils.policy).thenReturn(policy)
            Mockito.when(policy.stateCode).thenReturn(MOCK_STATE_CODE)
        }
    }
}

There is this class

public final class PolicySummaryUtils {
   public PolicySummaryResponse.Policy getPolicy() {
       return getPolicySummaryResponse().accounts.get(0).policies.get(0);
   }
}

 public static class Policy {
    @Expose
    public String sCode;
    @SerializedName("policySource")
}

I need to mock the state code inside viewModelTest. Is it possible to mock this? I have mocked policy and sCode is returned as null

@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class ViewModelTest{

    @Mock
    lateinit var summaryUtils: PolicySummaryUtils

    @Mock
    lateinit var policy: Policy

    @Test
    fun payBill_return_acceptedPayBillResponse(){
        return runTest {
            Mockito.when(summaryUtils.policyNumber).thenReturn(MOCK_POLICY_NO)
            Mockito.when(summaryUtils.policy).thenReturn(policy)
            Mockito.when(policy.stateCode).thenReturn(MOCK_STATE_CODE)
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧故 2025-02-14 05:31:50

尝试编写可测试的代码。例如,在您的情况下,您的课程是最终的,不能被模拟,然后您的类可以实现接口,那么您可以绝对模拟接口的方法。

您的班级是最终的,不能嘲笑

为什么?因为最后一堂课不能扩展。通过嘲笑类/接口,背后的技术是创建子类扩展/实现类/接口。然后,如果您的班级通过Final来防止扩展,则无法模拟它。

注意:您可以使用一些电力液体来模拟最终课程(例如 - PowerMockito),但我不建议这样做。

Try to write a testable code. Example in your case, Your class is final and cannot be mocked, then your class can implement an interface, then you can absolutely mock the methods of the interface.

Your class is final and cannot be mocked

Why? Because a final class cannot be extended. By mocking a class/interface, the technique behind is it creates a subclass extends/implements the class/interface. Then if your class prevents extending by having final, you cannot mock it.

Note: you can use some power libs to mock final class (e.g. - powermockito), but I would not recommend this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文