java單元測試小結


1. mock 構造函數

import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.tdtech.eplatform.gatekeeper.config.entity.Listenexternal;
import com.tdtech.eplatform.gatekeeper.constant.IConfigFileSet;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ExcelParasForListener.class)
/*
 * About @PowerMockIgnore:
 * http://www.ryanchapin.com/fv-b-4-816/Java-PowerMock-Could-not-reconfigure-JMX-java-lang-LinkageError-Solution.html
 */
@PowerMockIgnore({ "javax.management.*" })
public class ExcelParasForListenerTest {

    private ExcelParasForListener excelParasForListener = new ExcelParasForListener();

    @Test
    public void testLoadIPlistenerConfig() throws Exception {
        // mock ExcelReader constructor
        ExcelReader mocIPexcelReader = new ExcelReader(IConfigFileSet.easyconfTemplatePath,
                IConfigFileSet.sheetNameofListenIPMapping);
        PowerMockito.whenNew(ExcelReader.class)
                .withArguments(IConfigFileSet.importEasyconfFilePath, IConfigFileSet.sheetNameofListenIPMapping)
                .thenReturn(mocIPexcelReader);
        // test and verify
        ArrayList<Listenexternal> loadIPlistenerConfig = excelParasForListener.loadIPlistenerConfig();
        assertEquals("10.10.10.11", loadIPlistenerConfig.get(0).getListenIP());
        assertEquals(2404, loadIPlistenerConfig.get(0).getListenPort());
    }
}

可參考"如何使用PowerMock和Mockito來mock 1. 構造函數 2. 靜態函數 3. 枚舉實現的單例 4. 選擇參數值做為函數的返回值":

 

2. 測試異常

    @Rule
    public ExpectedException expectedEx = ExpectedException.none();

    @Test
    public void testLoadFileNotExists() throws Exception {
        
        ExcelReader mocGateexcelReader = new ExcelReader("mockNotExistFile", IConfigFileSet.sheetNameofGate);
        PowerMockito.whenNew(ExcelReader.class)
                .withArguments(IConfigFileSet.importEasyconfFilePath, IConfigFileSet.sheetNameofGate)
                .thenReturn(mocGateexcelReader);
     // 斷言拋出的異常類型, 不能與@Test(expected=BusinessException.class)方式共存
     expectedEx.expect(BusinessException.class);
   // 斷言得到的錯誤信息內容
expectedEx.expectMessage(
"文件格式有誤");
     // 被測試的方法在expectedEx.expectXxx() 方法后面
excelParasForGate.loadGateConfig(); }

擴展和總結: JUnit 4 如何正確測試異常
      測試異常的方法: 1.  try..catch 方式;    在catch中斷言:  拋出異常的 Class 類型;  拋出異常的具體類型(異常的 message 屬性中包含的字符串的斷定).

               2.  @Test(expected=Exception.class)  只能判斷出異常的類型,並無相應的注解能斷言出異常的更具體的信息.

               3.  @Rules public ExpectedException 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM