springboot下配置junit測試環境

項目中使用到了spring_boot,我想在項目中寫一些單元測試,但是由於對springboot 不熟悉並且springboot的中文資料非常的少,所以花了很長的時間才把springboot的junit測試環境搭好,雖然很簡單,但是也發出來給大家參考一下吧。

一 準備

1 首先編寫一個測試環境基類BaseDaoTest

package com.gome.superman.web.bussiness;

import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/** 
* @ClassName: BaseDaoTest 
* @Description: TODO
* @author liujie14
* @date 2016年7月8日 下午5:37:27 
*  
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DaoConfiguration.class )
@WebIntegrationTest({"server.port=0","management.port=0"})
@ActiveProfiles("test")
public abstract class BaseDaoTest {
}

2 編寫springboot配置類

package com.gome.superman.web.bussiness;
/**   
* @Title: DaoConfiguration.java 
* @Package com.gome.superman.common.sms 
* @Description: TODO
* @author heshengchao 
* @date 2016年7月8日 下午5:38:10 
* @version V1.0   
*/


import com.gome.dubbo.DubboAutoConfiguration;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

/** 
* @ClassName: DaoConfiguration 
* @Description: TODO
* @author liujie14
* @date 2016年7月8日 下午5:38:10 
*  
*/
@Configuration
@ComponentScan({"com.gome.superman.web.business"})
@Import({DubboAutoConfiguration.class} )
@ImportResource("classpath:spring/business-dubbo-consumer.xml")
@SpringBootApplication
public class DaoConfiguration {
}


二 開始編寫測試

新建一個TestRest類 繼承 BaseDaoTest

package com.gome.superman.web.bussiness.controller;

import com.gome.superman.common.session.CacheSessionProvider;
import com.gome.superman.util.model.Response;
import com.gome.superman.util.redis.RedisUtils;
import com.gome.superman.web.business.controller.BrandController;
import com.gome.superman.web.business.controller.SuperManTradeRegistController;
import com.gome.superman.web.bussiness.BaseDaoTest;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.io.Serializable;
import java.util.Map;

/**
 * @Author zengyu
 * @Date 2016-07-18
 * @Email [email protected]
 * @Desc
 */

//用於自動化測試整個註冊流程
public class testRegist extends BaseDaoTest {
    @Autowired
    SuperManTradeRegistController superManTradeRegistController;


    @Test
    public void testRgist()
    {
        Response response  = superManTradeRegistController.validatePhoneNum("18681277109");
        //效驗手機號。
        Assert.assertTrue( response.isSuccess() );
        //發送短信 ,獲取驗證碼
        response =   superManTradeRegistController.sendMessage( null , "18681277109" );
        Assert.assertTrue( response.isSuccess() );
        String token     = response.getResult().toString();
        String  msgCode  = getMsgCode( token );
        response = superManTradeRegistController.messageCodeValidate( token , msgCode );
        Assert.assertTrue( response.isSuccess() );
        //根據token獲取驗證碼
        // 註冊資料
        String msBase         = "{     \"tradePhone\": \"18681277109\",     \"tradePwd\": \"abcd1111\"   }";
        String msSecurityInfo = "{     \"securityQuestionId\": 1,     \"securityQuestionAnswer\": \"sdad\"   }";
        response = superManTradeRegistController.regist( msBase , msSecurityInfo , token );
        System.out.println( response );
        Assert.assertTrue( response.isSuccess() );
        String baseInfos = "{     \"id\": 11,     \"companyName\": \"llalal\",     \"provinceId\": 1,     \"cityId\": 2,     \"districtId\": 3,     \"provinceName\": \"llalal\",     \"cityName\": \"xnclx\",     \"districtName\": \"slxx\",     \"tradePhone\": 18681277107,     \"linkman\": \"sdalnvkd\",     \"linkmanPhone\": 18681277109,     \"companyPhone\": 2081996,     \"companyDetailAddress\": \"nsdadnosfa\"   }";
        String brandsInfo = "[     {       \"brandId\": 2,       \"brandName\": \"xniovadv\",       \"brandEngName\": \"onzxvizo\"     }   ]";
        String categoriesInfo = "[]";
        response = superManTradeRegistController.saveSellerAuthenticationInformation( baseInfos , brandsInfo , categoriesInfo );
        System.out.println(response);
        Assert.assertTrue( response.isSuccess() );

    }

    public String getMsgCode( String token ){
//        Map<String, Serializable> session = (Map<String, Serializable>) CacheSessionProvider.unserialize( RedisUtils.binaryGet(  token.getBytes()) );
//        return (String) session.get("token");
        return RedisUtils.get(token);
    }



}

三 注意事項

看了前面一大段代碼,相信大家也感覺比較迷糊。使用spingboot一個很重要的地方就是要對它的各種註解都要很熟悉,在這裏我就對幾個註解說下自己的理解吧。

先看兩個註解:

@Import   @ImportResource

他們在springboot的官方文檔中是這樣介紹的

/**
 * Indicates one or more {@link Configuration @Configuration} classes to import.
 *
 * <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
 * Allows for importing {@code @Configuration} classes, {@link ImportSelector} and
 * {@link ImportBeanDefinitionRegistrar} implementations, as well as regular component
 * classes (as of 4.2; analogous to {@link AnnotationConfigApplicationContext#register}).
 *
 * <p>{@code @Bean} definitions declared in imported {@code @Configuration} classes should be
 * accessed by using {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
 * injection. Either the bean itself can be autowired, or the configuration class instance
 * declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly
 * navigation between {@code @Configuration} class methods.
 *
 * <p>May be declared at the class level or as a meta-annotation.
 *
 * <p>If XML or other non-{@code @Configuration} bean definition resources need to be
 * imported, use the {@link ImportResource @ImportResource} annotation instead.
意思就是。 @import 相當於我們在進行xml配置中的<import/>標籤。用來包含一些被@Configruation標記的類。

@ImportResource  用來引入一些xml文件,從而使我們可以既用@Configuration類來配置,又可以用xml文件進行配置。


再看@SpringBootApplication

這個註解在源碼中是這樣定義的

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {

可見,使用了這個註解後,被標記的類就擁有@ComponentScan  @Configuration 等等的特性。



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