mock nested method calls using mockito

前端 未结 3 1461
深忆病人
深忆病人 2021-02-02 06:05

I have got 4 classes lets says A, B, C, D each calling on methods from another one.

now I have mocked class A, and want to mock a method using mockito

A          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 06:49

    Try by creating mock of each of the nested object and then mock the individual method called by each of these object.

    If the target code is like:

    public Class MyTargetClass {
    
        public String getMyState(MyClass abc){
    
           return abc.getCountry().getState();
        }
    }
    

    Then to test this line we can create mocks of each of the individual nested objects like below:

    public Class MyTestCase{
    
    @Mock
    private MyTargetClass myTargetClassMock;
    
    @Mock
    private MyClass myclassMockObj;
    
    @Mock
    private Country countryMockObj;
    
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }
    
        @Test
        public void test01(){
    
           when(myclassMockObj.getCountry()).thenReturn(countryMockObj);
           when(countryMockObj.getState()).thenReturn("MY_TEST_STATE");
           Assert.assertEquals("MY_TEST_STATE", myTargetClassMock.getMyState(myclassMockObj));
        }
    }
    

提交回复
热议问题