JUnit In Action 学习笔记

 (1)回归测试----在已经存在的代码中加入新的代码时以保证代码仍然能够正常运行的测试叫回归测试(regression test)。

(2)Ant

// P124页
// 后面还有一个生成 xml 格式的 report 说明
// 自动找出要运行的测试

// 给项目命名,并设定黙认目标以便测试
<project name="sampling" default="test">

 // 你包含一个 build.properties 文件
 // 这个文件包括由于依赖于执行文件而必须在用户的系统上改变的 Ant 属性。
 <property file="build.properties" />

 <property name="src.dir" location="src" />
 <property name="src.java.dir" location="${src.dir}/java" />
 <property name="src.test.dir" location="${src.dir}/test" />
 
 <property name="target.dir" location="target" />
 <property name="target.classes.java.dir" location="${target.dir}/classes/java" />
 <property name="target.classes.test.dir" location="${target.dir}/classes/test" />
 

 // 定义一个名为 compile.java 的目标来编译 java 产品源码
 <target name="compile.java">
  
  // 保证产生产品类文件的目录存在
  <mkdir dir="${target.classes.java.dir}" />

  // 调用 java 编译器(javac)并且传给它目标目录
  <javac destdir="${target.classes.java.dir}">

   // 告诉 javac 需要编译的源码在哪
   <src path="${src.java.dir}" />
  </javac>
 </target>

 // 目标 compile.test 依赖于目标 compile.java
 <target name="compile.test" depends="compile.java">
  <mkdir dir="${target.classes.test.dir}" />
  <javac destdir="${target.classes.test.dir}">
   <src path="${src.test.dir}" />

   // 你得添加一条嵌套的 classpath 元素
   <classpath>
    <pathelement location="${target.classes.java.dir}" />
   </classpath>
  </javac>
 </target>

 // 创建一个自动调用目标 compile.java 和 compile.test 编译目标
 <target name="compile" depends="compile.java,compile.test" />


 // 构建文件的 test 目标
 // 如果你让 Ant 运行测试目标,它会先运行编译目标
 <target name="test" depends="compile">
 
  // printsummary 属性表明在测试的最后一行输出一个单行的概要
  // 通过把 fork 设为 yes,你强制 Ant 对每个测试分别使用一个单独的 java 虚拟机(JVM)
  // 属性 haltonerror 和 haltonfailure 表明如果失败或产生错误将停止编译
  <junit printsummary="yes" haltοnerrοr="yes" haltonfailure="yes" fork="yes">

   // 配置 junit 任务格式器,用纯文本并且输出文本到控制台
   <formatter type="plain" usefile="false" />

   <test name="junitbook.sampling.TestDefaultController" />
   <classpath>
    <pathelement location="${target.classes.java.dir}" />
    <pathelement location="${target.classes.test.dir}" />
   </classpath>
  </junit>
 </target>


</project>

(3)stub 可以用来代替文件系统、到服务器的连接、数据库等。mock objects 可以用来代替单一的类

(4)Jetty

package edu.dhu.zkl.jetty;

import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpServer;
import org.mortbay.http.SocketListener;
import org.mortbay.http.handler.ResourceHandler;

public class JettySample {
 public static void main(String[] args) throws Exception {
  HttpServer server = new HttpServer();
  SocketListener listener = new SocketListener();
  listener.setPort(8081);
  server.addListener(listener);
  
  HttpContext context = new HttpContext();
  context.setContextPath("/");
  context.setResourceBase("./");
  context.addHandler( new ResourceHandler() );
  server.addContext(context);
  
  server.start();
 }
}

运行这个程序,然后在浏览器输入 http://localhost:8081/ 就可以看到项目下的所有资源。

(5)用 Jetty 来演示一个 Stub 的测试(注意加入 servelt-api.jar 和 jetty.jar )

两个类,一个 TestWebClientSetup1 用来内嵌 Jetty 服务器,另一个 TestWebClient1 简单的测试案例

package edu.dhu.zkl.jetty.test;

import java.io.IOException;
import java.io.OutputStream;

import junit.extensions.TestSetup;
import junit.framework.Test;

import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpFields;
import org.mortbay.http.HttpRequest;
import org.mortbay.http.HttpResponse;
import org.mortbay.http.HttpServer;
import org.mortbay.http.SocketListener;
import org.mortbay.http.handler.AbstractHttpHandler;
import org.mortbay.http.handler.NotFoundHandler;
import org.mortbay.util.ByteArrayISO8859Writer;

public class TestWebClientSetup1 extends TestSetup {
 protected static HttpServer server;
 
 public TestWebClientSetup1(Test suite) {
  super(suite);
 }
 
 protected void setUp() throws Exception {
  server = new HttpServer();
  SocketListener listener = new SocketListener();
  listener.setPort(8081);
  server.addListener(listener);
  
  HttpContext context1 = new HttpContext();
  context1.setContextPath("/testGetContentOk");
  context1.addHandler(new TestGetContentOkHandler());
  server.addContext(context1);
  
  HttpContext context2 = new HttpContext();
  context2.setContextPath("/testGetContentNotFound");
  context2.addHandler(new NotFoundHandler());
  server.addContext(context2);
  
  HttpContext context3 = new HttpContext();
  context3.setContextPath("/testGetContentServerError");
  context3.addHandler(new TestGetContentServerErrorHandler());
  server.addContext(context3);
  
  server.start();
 }
 
 protected void tearDown() throws Exception {
  server.stop();
 }
 
 private class TestGetContentOkHandler extends AbstractHttpHandler {
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public void handle( String pathInContext, String pathParams,
    HttpRequest request, HttpResponse response ) throws IOException {
   OutputStream out = response.getOutputStream();
   ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
   writer.write("It works");
   writer.flush();
   response.setIntField( HttpFields.__ContentLength, writer.size() );
   writer.writeTo(out);
   out.flush();
   request.setHandled(true);
  }
 }
 
 private class TestGetContentServerErrorHandler extends AbstractHttpHandler {
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public void handle(String pathInContext, String pathParams,
    HttpRequest request, HttpResponse response ) throws IOException {
   response.sendError(HttpResponse.__503_Service_Unavailable);
  }
 }
}

package edu.dhu.zkl.jetty.test;

import java.net.URL;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import edu.dhu.zkl.jetty.WebClient;

public class TestWebClient1 extends TestCase {
 public static Test suite() {
  TestSuite suite = new TestSuite();
  suite.addTestSuite(TestWebClient1.class);
  
  return new TestWebClientSetup1(suite);
 }
 
 public void testGetContentOk() throws Exception {
  WebClient client = new WebClient();
  
  String result = client.getContent(new URL(
    "http://localhost:8081/testGetContentOk" ) );
  
  assertEquals( "It works", result );
 }
 
 public void testGetContentNotFound() throws Exception {
  WebClient client = new WebClient();
  
  String result = client.getContent(new URL(
    "http://localhost:8081/testGetContentNotFound" ) );
  
  assertNull(result);
 }
 
 public void testGetContentServerError() throws Exception {
  WebClient client = new WebClient();
  
  String result = client.getContent(new URL(
    "http://localhost:8081/testGetContentServerError" ) );
  
  assertNull(result);
 }
}

还有一个 WebClient 类,被测类

package edu.dhu.zkl.jetty;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.IOException;

public class WebClient
{
    public String getContent(URL url)
    {
        StringBuffer content = new StringBuffer();

        try
        {
            HttpURLConnection connection =
                (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);

            InputStream is = connection.getInputStream();

            byte[] buffer = new byte[2048];
            int count;
            while (-1 != (count = is.read(buffer)))
            {
                content.append(new String(buffer, 0, count));
            }
        }
        catch (IOException e)
        {
            return null;
        }

        return content.toString();
    }
}

(6)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JUnit学习笔记精要》是一本介绍JUnit测试框架的学习资料,可以从CSDN下载。JUnit是一个开源的Java单元测试框架,用于简化和自动化开发者编写和执行单元测试的过程。JUnit学习对于提高代码质量、减少bug的产生以及提高开发效率具有重要意义。 这本《JUnit学习笔记精要》将帮助读者从零开始掌握JUnit的基本概念和用法。书中首先介绍了JUnit的起源和发展历程,让读者了解JUnit的背景和重要性。然后详细讲解了JUnit的安装和配置,帮助读者快速上手使用该测试框架。 接下来,书中深入介绍了JUnit的各种注解和断言方法。JUnit的注解用于标记测试方法,通过使用不同的注解,可以控制测试方法的执行顺序、重复执行次数等。而JUnit的断言方法则用于验证测试结果是否符合预期。书中通过大量的示例代码和实际案例,详细讲解了如何使用这些注解和断言方法。 此外,书中还介绍了如何构建复杂的测试套件、如何使用参数化测试和如何处理异常测试。这些高级主题能够帮助读者进一步提升自己的单元测试技能,实现更全面的测试覆盖和更准确的测试结果。 总之,《JUnit学习笔记精要》是一本系统、实用的学习资料,适合想要学习JUnit的开发者。通过下载这本书,读者可以更好地理解和掌握JUnit的各种概念和用法,提高软件开发的质量和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值