Spring測試環境

在學習過程中,有的時候有一個小功能需要測試,假如這個功能是關於spring的,那麼首先得加載spring的各種配置文件吧,這是省不了的,如下:

public static void main(String[] args) throws InterruptedException {
        ApplicationContext app=new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        CacheTestService cacheTestService = app.getBean(CacheTestService.class);
    }

這樣子其實不方便,而且取出Bean也不能使用註解方式,每次去getBean多麻煩啊!

當然,如果在web環境中,比如tomcat中,那麼啓動好了tomcat,只要配置得當,那麼是不用手動寫代碼去加載spring配置文件的,但是我們的前提是測試!測試一個小功能還要去啓動tomcat,還有去配置啓動環境?多麻煩,多浪費時間。

所以,我們使用spring的test模塊,再配合Junit,就非常完美的實現了加載spring配置文件,並且也可以使用註解方式獲得注入的Bean

如下:

maven主要依賴,spring其他必不可少的依賴此處省略..............

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

測試類

package com.stu;

import com.stu.service.CacheTestService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @功能:
 * @開發者: 大BUG
 * @編寫時間: 2018/11/27 14:22
 */
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TestNotMain extends AbstractJUnit4SpringContextTests {
    private static Logger log= LogManager.getLogger(TestNotMain.class);
    @Autowired
    private CacheTestService cacheTestService;
    @Test
    public void test() throws InterruptedException {
        log.debug(cacheTestService.getTime());
    }
}

OK啦,只需加上這兩個註解spring的測試環境就好了

@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章