Mocking a Spring service with Mockito for a JUnit test

First define the bean to be mocked in your XML like this

<bean id="mockedService" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="a.b.c.MockedServiceInterface" />
</bean>

Then you can inject it into other beans as usual:

<bean id="testedService" class="a.b.c.TestedServiceImpl">
    <property name="mockedService" ref="mockedService" />
</bean>

And now we can override the behaviour of the mockedService in our JUnit test

MockedServiceInterface mockedService = (MockedServiceInterface) applicationContext.getBean("mockedService");    

doAnswer(new Answer<String>() {

    @Override
    public String answer(InvocationOnMock invocationOnMock) throws Throwable {
        String arg1 = (String) invocationOnMock.getArguments()[0];
        AnyClass arg2 = (AnyClass) invocationOnMock.getArguments()[1];

        return "The result.";
    }

}).when(mockedService).doSomethingUseful(any(String.class), any(AnyClass.class));