Mockito - intercept any method invocation on a mock

后端 未结 1 772
执念已碎
执念已碎 2020-12-30 23:02

Is it possible to intercept all method invocations on a mock in a generic way?

Example

Given a vendor provided class such as:



        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 23:44

    I think what you want is:

    VendorObject vo = mock(VendorObject.class, new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
    
            // 1. Check if method exists on RedirectToObject.
            // 2a. If it does, call the method with the args and return the
            // result.
            // 2b. If it does not, throw an exception to fail the unit test.
    
        }
    });
    

    Of course, if you want to use this approach frequently, no need for the Answer to be anonymous.

    From the documentation: "It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems." Sounds like you.

    0 讨论(0)
提交回复
热议问题