在方法上具有 @Retryable 注释的模拟 Spring @Service 失败并出现 UnfinishedVerificationException

2024-04-27

我正在使用 Spring Boot1.4.0.RELEASE with spring-boot-starter-batch, spring-boot-starter-aop and spring-retry

我有一个 Spring 集成测试@Service这是在运行时被模拟的。我注意到如果@Service类包含任何@Retryable其方法上的注释,那么它似乎会干扰Mockito.verify(),我得到一个UnfinishedVerificationException。我想这一定与spring-aop?如果我全部注释掉@Retryable中的注释@Service然后再次验证工作正常。

我创建了一个github项目 https://github.com/pearj/spring-boot-batch-retry-issue这说明了这个问题。

它失败于sample.batch.MockBatchTestWithRetryVerificationFailures.batchTest() at validateMockitoUsage();

像这样的东西:

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()

不过我还有另一堂课(sample.batch.MockBatchTestWithNoRetryWorking.batchTest())带着嘲笑@Service没有任何@Retryable注释和验证工作正常。

我究竟做错了什么?

在我的 pom.xml 中,我有以下内容:

<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>
...

然后是所有相关的Java类

@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);
        }
    }
}

编辑:根据我整理的示例项目更新了问题和代码以显示问题。


所以在看了类似的之后github问题 https://github.com/spring-projects/spring-boot/issues/5837 for spring-boot

我发现有一个额外的代理妨碍了。我通过手动解开 aop 类发现了一个令人讨厌的 hack,使验证工作正常,即:

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

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

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

希望这个问题可以像上面的 github 问题一样得到解决。我会提出一个问题,看看我能走多远。

编辑:提出了github问题 https://github.com/spring-projects/spring-boot/issues/6828

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在方法上具有 @Retryable 注释的模拟 Spring @Service 失败并出现 UnfinishedVerificationException 的相关文章

随机推荐