模拟使用Mockito在最后一堂课内的方法
我需要在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试编写可测试的代码。例如,在您的情况下,您的课程是最终的,不能被模拟,然后您的类可以实现接口,那么您可以绝对模拟接口的方法。
为什么?因为最后一堂课不能扩展。通过嘲笑类/接口,背后的技术是创建子类扩展/实现类/接口。然后,如果您的班级通过
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.
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.