系列文章
《單元測試—— Spring 環境下測試之 SpringJUnit4ClassRunner》
Maven依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
<scope>test</scope>
</dependency>
測試代碼
package com.zhaoxj_2017.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.text.SimpleDateFormat;
import java.util.Date;
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest( classes = {ScheduleThreadTest.class, ScheduleThreadTest.TestConfig.class} )
public class ScheduleThreadTest {
@Test
public void testCron() {
try {
Thread.sleep(30000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Configuration
@EnableScheduling
public static class TestConfig {
@Bean
public ScheduleTask getScheduleTask() {
return new ScheduleTask();
}
}
}
@Component
class ScheduleTask {
@Scheduled(fixedRateString="1000")
public void execute() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.format(new Date().getTime()));
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}