Home > Software engineering >  Mock a method that's inside a final class using Mockito
Mock a method that's inside a final class using Mockito

Time:06-16

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)
        }
    }
}

CodePudding user response:

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.

  • Related