java单元测试小结
2024-09-06 11:45:59
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
最新文章
- 前端开发:css技巧,如何设置select、radio 、 checkbox 、file这些不可直接设置的样式 。
- zigbee学习之路(二)点亮LED
- linux 查找目录或文件
- POJ 1469
- 随机森林——Random Forests
- wikioi3363支线剧情(挖个坑,不会做。。。)
- 详解CSS网页布局中默认字体样式
- Python 做过哪些有趣的项目
- 最小生成树算法prim and kruskal
- 使用Maven快速创建一个SpringMVC工程步骤
- Linux下jira自启动设置
- ELK学习总结(1-3)倒排索引
- 单例模式详解及java常用类
- Unicode字符编码表
- Junit的套件使用
- pipenv+sublime text3 配置
- 2018.10.31 bzoj3339&&3585mex(主席树)
- 一键安装 zabbix 2.0 版本 脚本
- linux内核自己添加模块(内核版本:3.0.101)
- SQL 时间及字符串操作