1. 程式人生 > >IDEA中利用JUnit進行單元測試

IDEA中利用JUnit進行單元測試

開啟IntelliJ IDEA工具,Alt+Ctrl+S,彈出視窗如下:


在文字框中輸入Plugin進行外掛搜尋設定。


點選按鈕,從外掛資源庫中安裝新的外掛。

從外掛資源庫中搜索JunitGenerator V2.0版本,在外掛位置,滑鼠右擊



選擇Download and Install ,在彈出的對話方塊中選擇yes按鈕,點選OK之後在需要重啟下工具,選擇Restart按鈕,到此JunitGenerator2.0 外掛安裝完畢.

現在可通過此工具自動完成test類的生成了,在需要進行單元測試的類中Alt+Insert,


測試類中使用的相關注解跟程式碼如下:

package test.RXTemplateService;

import RXTemplateService.YhService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * YhService Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since <pre>���� 19, 2013</pre>
 */

/*用於配置spring中測試的環境*/
@RunWith(SpringJUnit4ClassRunner.class)
/*
用來指定載入的Spring配置檔案的位置,會載入預設配置檔案
@ContextConfiguration 註解有以下兩個常用的屬性:
locations:可以通過該屬性手工指定 Spring 配置檔案所在的位置,可以指定一個或多個 Spring 配置檔案。
inheritLocations:是否要繼承父測試用例類中的 Spring 配置檔案,預設為 true。
*/
@ContextConfiguration(locations = "classpath:test/RXTemplateService/applicationContext.xml")
/*
@TransactionConfiguration是配置事務情況的註解.
第一個引數transactionManager是你在applicationContext.xml或bean.xml中定義的事務管理器的bean的id;
第二個引數defaultRollback是表示測試完成後事務是否會滾 引數是布林型的 預設就是true 但強烈建議寫上true
*/
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class YhServiceTest {
    @Resource
    private YhService yhService;

    @Before
    public void before() throws Exception {
    }

    @After
    public void after() throws Exception {
    }

    /**
     * Method: checkDlzhAndDlmm(String dlzh, String dlmm)
     */
    @Test
    public void testCheckDlzhAndDlmm() throws Exception {
        assert true : yhService.checkDlzhAndDlmm("wbb", "wbb");
    }

    /**
     * Method: resetMm(String xmm, Integer id)
     */
    @Test
    public void testResetMm() throws Exception {
        yhService.resetMm("admin", 1);
    }

    /**
     * Method: yhSave(T_XT_YH yh)
     */
    @Test
    @Rollback(false)
    public void testYhSave() throws Exception {
//TODO: Test goes here...
    }

    /**
     * Method: yhDelete(String ids)
     */
    @Test
    public void testYhDelete() throws Exception {
//TODO: Test goes here...
    }

    /**
     * Method: checkDlzh(String dlzh, Integer id)
     */
    @Test
    public void testCheckDlzh() throws Exception {
//TODO: Test goes here...
    }

    /**
     * Method: findYhById(Integer id)
     */
    @Test
    public void testFindYhById() throws Exception {
//TODO: Test goes here...
    }

    /**
     * Method: getYhList(int pageNo, int pageSize, Integer ssjgId)
     */
    @Test
    public void testGetYhList() throws Exception {
//TODO: Test goes here...
    }
}