javamockitoverify

Mockito, verify for function invocation when argument is function


Could you suggest me how to check of function invocation if it argument is the function too via Mockito.

Let's assume three service classes, details omitted for brevity

class SomeService {
 public void process(SomeType type1) {...}
 public void process(AnotherType type2) {...}
}

class AnotherService {
 public SomeType anotherProcess(args) {...}
}

class ServiceForTests {
 public void mainProcess() {
    someService.process(anotherService.anotherProcess(args))
 }
}

I need to check that process invokes in ServiceForTests.mainProcess.

The code verify(someService).process(any(SomeType.class)) has failed because of argument difference. Wanted: any of SomeType, but Actual: anotherService.anotherProcess.

I cant to test with verify(someService).process(any()) because of SomeService.process is overloaded.


Solution

  • Please confirm if you are doing everything correctly or maybe I have understood your question wrong.

    I reproduced it in my local and it seems to work okay for me.

    Reproduced Code

    SomeService
    public class SomeService {
        public void process(String T1) {}
        public void process(Map<String,String> T2) {}
    }
    
    AnotherService
    public class AnotherService {
        public String anotherProcess() {
            return "Hello World";
        }
    }
    
    ServiceForTests
    public class ServiceForTests {
        public SomeService someService;
        public AnotherService anotherService;
    
        public ServiceForTests(SomeService someService, AnotherService anotherService) {
            this.someService = someService;
            this.anotherService = anotherService;
        }
    
        public void mainProcess() {
            someService.process(anotherService.anotherProcess());
        }
    }
    
    TestServiceForTests
    @ExtendWith(MockitoExtension.class)
    public class TestServiceForTests {
    
        ServiceForTests classUnderTest;
    
        @Mock
        private SomeService someService;
        @Mock
        private AnotherService anotherService;
    
        @BeforeEach
        public void setUp() {
            classUnderTest = new ServiceForTests(someService, anotherService);
        }
    
        @Test
        public void testMainProcess() {
            doReturn("Hello World!")
                    .when(anotherService)
                    .anotherProcess();
    
            classUnderTest.mainProcess();
    
            verify(someService)
                    .process(any(String.class));
        }
    }