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 

原文地址:https://www.cnblogs.com/eaglediao/p/7492810.html