Junit使用方法
前言
在开发过程中,为了测试某个方法的正确性,往往在写完方法之后进行测试一下。在代码比较简单,很少对其他模块依赖的情况下,可以使用简单的创建对象,调用对象的方法来进行测试。但是这种测试往往比较复杂,会在代码中添加main方法,如果忘记注释掉这些代码,往往会出现错误等。下面就来介绍一种专门用来做单元测试的工具Junit。
简介
JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。 JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。[1]
依赖
使用Junit需要其依赖的jar包:
maven格式为:
<!--https://mvnrepository.com/artifact/junit/junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
</dependency>
案例
引用上述jar包后就可以直接使用Junit进行单元测试了
/**
* @author 合肥工业大学 管理学院 周永行
* @email:[email protected]
*/
public class TestStudy {
/**
* @使用URL对象打开
* @param url
*/
public void downloadPage(String url){
String temp="";
StringBuffer buffer=new StringBuffer();
InputStream inputStream=null;
try {
URL pageUrl = new URL(url);
inputStream=pageUrl.openStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
temp=reader.readLine();
while(temp!=null){
buffer.append("\n");
buffer.append(temp);
temp=reader.readLine();
}
}catch (MalformedURLException e){
System.out.println(e);
}catch (IOException e){
System.out.println(e);
}finally {
if(inputStream!=null){
try{
inputStream.close();
}catch (IOException e){
System.out.println("网络流关闭失败");
}
}
}
System.out.println(buffer.toString());
}
/**
*@使用HttpClien下载网页
*
*/
public void getPageByHttpClient(String url){
CloseableHttpClient client= HttpClientBuilder.create().build();
HttpGet httpGet=new HttpGet(url);
HttpResponse response=null;
HttpEntity entity=null;
String html=null;
Header [] headers=null;
try{
response=client.execute(httpGet);
entity=response.getEntity();
headers=response.getAllHeaders();
if(entity!=null){
html= EntityUtils.toString(entity,"GBK");
}
for(Header header:headers){
System.out.println(header.getName()+":"+header.getValue());
}
EntityUtils.consume(entity);
client.close();
// System.out.println(html);
}catch (IOException e){
}
}
/**
*@告诉系统这是测试的方法,**测试方法的返回类型必须是void,而且被测试的类必须要有默认的构造方法,而且只能有默认的构造方法**,方法体内直接调用需要测试的方法
*
*/
@Test
public void atest(){
getPageByHttpClient("http://www.w3school.com.cn");
}
这是学习爬虫时写的程序,作者使用IDEA开发环境。点击一下注解旁边的额的小箭头就可以运行单元测试了