3

I'm using Spring Boot 1.4.0.RELEASE with spring-boot-starter-batch, spring-boot-starter-aop and spring-retry

I have a Spring Integration test that has a @Service which is mocked at runtime. I've noticed that if the @Service class contains any @Retryable annotations on its methods, then it appears to interfere with Mockito.verify(), I get a UnfinishedVerificationException. I presume this must be something to do with spring-aop? If I comment out all @Retryable annotations in the @Service then verify works ok again.

I have created a github project that demonstrates this issue.

It fails in sample.batch.MockBatchTestWithRetryVerificationFailures.batchTest() at validateMockitoUsage();

With something like:

12:05:36.554 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@5ec0a365 testClass = MockBatchTestWithRetryVerificationFailures, testInstance = sample.batch.MockBatchTestWithRetryVerificationFailures@5abca1e0, testMethod = batchTest@MockBatchTestWithRetryVerificationFailures, testException = org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
-> at sample.batch.service.MyRetryService$$FastClassBySpringCGLIB$$7573ce2a.invoke(<generated>)

Example of correct verification:
    verify(mock).doSomething()

However I have another class (sample.batch.MockBatchTestWithNoRetryWorking.batchTest()) with a mocked @Service that doesn't have any @Retryable annotation and verify works fine.

What am I doing wrong?

In my pom.xml I have the following:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>
...
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
    </dependency>
...

Then all the related Java Classes

@SpringBootApplication
@EnableBatchProcessing
@Configuration
@EnableRetry
public class SampleBatchApplication {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    @Autowired
    private MyRetryService myRetryService;

    @Autowired
    private MyServiceNoRetry myServiceNoRetry;

    @Bean
    protected Tasklet tasklet() {

        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution contribution,
                    ChunkContext context) {
                myServiceNoRetry.process();
                myRetryService.process();
                return RepeatStatus.FINISHED;
            }
        };

    }

    @Bean
    public Job job() throws Exception {
        return this.jobs.get("job").start(step1()).build();
    }

    @Bean
    protected Step step1() throws Exception {
        return this.steps.get("step1").tasklet(tasklet()).build();
    }


    public static void main(String[] args) throws Exception {
        // System.exit is common for Batch applications since the exit code can be used to
        // drive a workflow
        System.exit(SpringApplication
                .exit(SpringApplication.run(SampleBatchApplication.class, args)));
    }

    @Bean
    ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public JobRepository getJobRepo() throws Exception {
        return new MapJobRepositoryFactoryBean(transactionManager()).getObject();
    }

}

@Service
public class MyRetryService {

    public static final Logger LOG = LoggerFactory.getLogger(MyRetryService.class);

    @Retryable(maxAttempts = 5, include = RuntimeException.class, backoff = @Backoff(delay = 100, multiplier = 2))
    public boolean process() {

        double random = Math.random();

        LOG.info("Running process, random value {}", random);

        if (random > 0.2d) {
            throw new RuntimeException("Random fail time!");
        }

        return true;
    }

}

@Service
public class MyServiceNoRetry {

    public static final Logger LOG = LoggerFactory.getLogger(MyServiceNoRetry.class);

    public boolean process() {

        LOG.info("Running process that doesn't do retry");

        return true;
    }

}

@ActiveProfiles("Test")
@ContextConfiguration(classes = {SampleBatchApplication.class, MockBatchTestWithNoRetryWorking.MockedRetryService.class}, loader = AnnotationConfigContextLoader.class)
@RunWith(SpringRunner.class)
public class MockBatchTestWithNoRetryWorking {

    @Autowired
    MyServiceNoRetry service;

    @Test
    public void batchTest() {
        service.process();

        verify(service).process();
        validateMockitoUsage();
    }

    public static class MockedRetryService {
        @Bean
        @Primary
        public MyServiceNoRetry myService() {
            return mock(MyServiceNoRetry.class);
        }
    }
}

@ActiveProfiles("Test")
@ContextConfiguration(classes = { SampleBatchApplication.class,
        MockBatchTestWithRetryVerificationFailures.MockedRetryService.class },
                      loader = AnnotationConfigContextLoader.class)
@RunWith(SpringRunner.class)
public class MockBatchTestWithRetryVerificationFailures {

    @Autowired
    MyRetryService service;

    @Test
    public void batchTest() {
        service.process();

        verify(service).process();
        validateMockitoUsage();
    }

    public static class MockedRetryService {
        @Bean
        @Primary
        public MyRetryService myRetryService() {
            return mock(MyRetryService.class);
        }
    }
}

EDIT: Updated question and code based on a sample project I put together to show the problem.

Joel Pearson
  • 1,622
  • 1
  • 16
  • 28

2 Answers2

5

So after looking at a similar github issue for spring-boot

I found that there is an extra proxy getting in the way. I found a nasty hack by unwrapping the aop class by hand, makes verification work, ie:

@Test
public void batchTest() throws Exception {
    service.process();

    if (service instanceof Advised) {
        service = (MyRetryService) ((Advised) service).getTargetSource().getTarget();
    }

    verify(service).process();
    validateMockitoUsage();
}

Hopefully, this can be fixed similar to the above github issue. I'll raise an issue and see how far I get.

EDIT: Raised the github issue

Joel Pearson
  • 1,622
  • 1
  • 16
  • 28
3

After I've seen @Joel Pearsons answer, and especially the linked GitHub issue, I worked around this by temporarily using a static helper method that unwraps and verifies:

public static <T> T unwrapAndVerify(T mock, VerificationMode mode) {
    return ((T) Mockito.verify(AopTestUtils.getTargetObject(mock), mode));
}

With this method the only difference in the test cases is the verification call. There is no overhead other than this:

unwrapAndVerify(service, times(2)).process();

instead of

verify(service, times(2)).process();

Actually, it was even possible to name the helper method like the actual Mockito method, so that you only need to replace the import, but I didn't like the subsequent confusion.

However, unwrapping shouldn't be required if @MockBean is used instead of mock() to create the mocked bean. Spring Boot 1.4 supports this annotation.

Community
  • 1
  • 1
Andreas Siegel
  • 1,050
  • 8
  • 9