Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

java - How to test @Scheduled in Spring - not SpringBoot

I found many similar topics of this problem, but i still dont have a solution for my case. I want to test my scheduler in Spring 5 application and count how many times it invokes in some time.

Here is my scheduler:

@Component
public class CancelVisitScheduler {

    @Scheduled(fixedDelay = 10000, initialDelay = 10000)
    public void execute() {
        // do some things
    }
}

Im trying something like this:

import org.awaitility.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

class CancelVisitSchedulerTest {

    @Mock
    private CancelVisitScheduler cancelVisitScheduler;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void shouldExecuteAfter10Seconds() {
        await().atMost(Duration.ONE_MINUTE).untilAsserted(() -> verify(cancelVisitScheduler, times(4)).execute());
    }
}

but im getting error like this:

org.awaitility.core.ConditionTimeoutException: Assertion condition defined as a lambda expression in path....CancelVisitSchedulerTest 
Wanted but not invoked:
cancelVisitScheduler.execute();
-> at path....CancelVisitSchedulerTest.lambda$shouldExecuteAfter10Seconds$0(CancelVisitSchedulerTest.java:25)
Actually, there were zero interactions with this mock.
 within 60 seconds.

All answers which i found was to spring boot application, but I need a solution to spring. Is any simple option to do this?

question from:https://stackoverflow.com/questions/65911449/how-to-test-scheduled-in-spring-not-springboot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...