若是想讓junit和spring容器環境無縫對接的話,可使用以下方式:spring
import com.jd.ptest.service.ICronService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) //此處讀取spring的配置文件 public class CronServiceImplTest { @Autowired @SuppressWarnings("all") ICronService cronService; @Test public void addCron() { try { cronService.addCron(); } catch (Exception e) { e.printStackTrace(); } } }