中国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(1)
作者:未知 时间:2005-09-13 23:33 出处:Blog.ChinaUnix.net 责编:chinaitpower
              摘要:Focus on Mock Object(1)

Testing in isolation of Mock Objects: write focused tests that test only a single method, without side effects resulting from other objects relative.

A simple example: Account Manager Problem(based on a Database environment)


Application analysis:
class Account--two attributes: accountId and balance. Three methods: debit(-), credit(+), getBalance--quite simple and not related to other object or enrionment.
class AccountManager--Manage Account, default connect DB to get data from it. Two methods: findAccountForUser and updateAccount. Closely related to object Account and enrionment DataBase.--must be mocked to fit for unit-test.
class AccountService--one attributes: accountManager which you can confige by yourself. Two methods: setAccountManager and transfer.--This is the class we want to test. The transfer method will be testd with class MockAccountManage which implements AccountManager to let the unit-test run easily.

In the real way, solid class which implements AccountManager may connect to a database to gain the data requested. With the MockAccoundManager which tester created to replaced the default behavier of AccounManager, under your control, we can test AccountService singly.

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


import junit.framework.TestCase;

public class TestAccountService extends TestCase {
 public void testTransferOK() {
  MockAccountManager mockAccountManager = new MockAccountManager();
  Account senderAccount = new Account("1", 200);
  Account beneficiaryAccount = new Account("2", 100);
  
  mockAccountManager.addAccount("1", senderAccount);
  mockAccountManager.addAccount("2", beneficiaryAccount);
  
  AccountService accountService = new AccountService();
  
  accountService.setAccountManager(mockAccountManager);
  
  accountService.transfer("1", "2", 50);
  
  assertEquals(150, senderAccount.getBalance());
  assertEquals(150, beneficiaryAccount.getBalance());
 }
}

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