1. 程式人生 > >基於junit的單元測試類編寫

基於junit的單元測試類編寫

frame eos set new common cep resource build gson

首先定義抽象類BaseTest

package com.geostar.gfstack.operationcenter.common.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/spring/applicationContext.xml")
public abstract class BaseTest {

    private static final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    public static void printJson(Object obj){
        print("*************************** printJson start ***************************");
        print(gson.toJson(obj));
        print("**************************** printJson end ****************************");
    }

    public static void print(Object obj){
        System.out.println(obj);
    }

}

  

實現類直接使用@Resource註入bean,使用@Test註解編寫測試方法

package com.geostar.gfstack.operationcenter.core.cloud.service.test;

import com.geostar.gfstack.operationcenter.common.exception.GeoStackException;
import com.geostar.gfstack.operationcenter.common.util.BaseTest;
import com.geostar.gfstack.operationcenter.core.cloud.log.OrdersProcessLog;
import com.geostar.gfstack.operationcenter.core.cloud.model.Orders;
import com.geostar.gfstack.operationcenter.core.cloud.service.IOrderService;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.List;

public class OrderServiceTest extends BaseTest {

    @Resource
    private IOrderService orderService;

    @Test
    public void saveOrders() throws GeoStackException {
        Orders orders = new Orders();
        orders.setOrderId(String.valueOf(System.currentTimeMillis()));
        orders.setOrderRemark("測試訂單");
        orders.setCheckState("99999");
        orderService.saveOrders(orders);
    }

}

  

基於junit的單元測試類編寫