简体   繁体   中英

Unit test - Problems testing @Retryable and @Recover

I have a component that's using @Retryable annotation and another service using that component. So I'm trying to test that the component using @Retryable annotation is actually retrying.

I've tried every solution there is on the web right now but nothing worked for me. I'm trying to create a unit test for this and not integration test. So far I've managed to get to the exception that's supposed to be thrown and @Retryable wasn't even retrying, the method just threw the exception and thats it.

This is the component using Retryable annotation:

@Component
public class OurComponent {

    @Retryable(maxAttempts = 10,
            backoff = @Backoff(delay = 2000),
            value = {someException.class}
    )
    public void someMethod(SomeObject someObject) throws someException {
        Object createObject = anotherMethod(someObject); //this method throws someException
        ...
    }
}

And the service using this ourComponent:

@Service
public class someService {

    private final OurComponent ourComponent;

    public SomeService(OurComponent ourComponent) {
         this.ourComponent = ourComponent;
    }

    ...


    public void methodUsingComponent() {
         SomeObject someObject = new SomeObject(args);
         ourComponent.someMethod(someObject);
    }
}

Now I've tried to @InjectMocks and @MockBean this service and component but it still didn't work. Is it even possible to test @Retryable annotation without doing integration test?

If you use a unit test that doesn't use spring at all, you won't be able to test it easily.

This is due to the fact that annotations like this are recognized by spring and the corresponding bean is wrapped with a runtime-generated proxy that implements the "retry" logic.

Now, if you don't have spring who triggers all this mechanism, this @Retryable annotation is basically useless, mockito doesn't know anything about, so is Junit.

You could try to create a proxy like this manually (check what logic spring-retry invokes) but it looks to be an overkill. And frankly speaking, it doesn't give you anything. Unit test should check the functionality of your code and not the logic behind spring retry that was implemented by somewhere else and tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM