中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 软件工程 > 综合文章
Focus on Mock Object(2)
作者:未知 时间:2005-09-13 23:33 出处:Blog.ChinaUnix.net 责编:chinaitpower
              摘要:Focus on Mock Object(2)

A more complex environment: web application based on a Web Server. Here we compare servious ways to simulate the Web Server Condition with Mock Object.


The original WebClient source:

src: http://blog.chinaunix.net/resserver.php?blogId=8755&resource=junit72.txt

As you can see java.net.HttpURLConnection and java.net.URL are related to the Web Server wanted to mock.

Someone may think directly: just mock it with its subclass as MockHttpURLConnetion and MockURL.

public void testGetContentOk() throws Exception {
   MockHttpURLConnection mockConnection = new MockHttpURLConnection();
   mockConnection.setupGetInputStream(new ByteArrayInputStream("It works".getBytes()));
   MockURL mockURL = new MockURL();
 
   mockURL.setupOpenConnection(mockConnection);
 
   WebClient client = new WebClient();
   String result = client.getContent(mockURL);
   assertEquals("It works", result);
}

But one thing they forgot: the java.net.URL is a final class, which meants it couldn't be extended. Then, How can we mock it besides this way?

Now, we find we must do something to the class java.net.URL, let us easily to mock it.

improved src: http://blog.chinaunix.net/resserver.php?blogId=8755&resource=junit73.txt

You can find that with this alternaive we can mock it easiler.

private class TestableWebClient extends WebClient {
   private HttpURLConnection connection;
   public void setHttpURLConnection(HttpURLConnection connection) {
      this.connection = connection;
   }
   public HttpURLConnection createHttpURLConnection(URL url) throws IOException {
      return this.connection;
   }
}

As you can see, with the class TestableWebClient extended from WebClient, you can set the HttpURLConnection yourself and artfully avoid the URL problem.

Test Case src with the improvement: http://blog.chinaunix.net/resserver.php?blogId=8755&resource=junit74.txt

"This is a common refactoring approach called Method Factory refactoring, which is especially useful when the class to mock has no interface. The strategy is to extend that class, add some setter methods to control it, and override some of its getter methods to return what you want for the test."

But what are you truely test? The subclass which behaviors have been changed, not the original one.

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有