轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)

1.源代码
轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)AccountService.java
package com.account;
import com.account.Account;
import com.account.AccountManager;
public class AccountService
{
//使用的账户管理器实现
private AccountManager accountManager;
//设置账户管理器实现的设置方法
public void setAccountManager( AccountManager manager )
{
this.accountManager = manager;
}
//一个设置客户经理实现从账户到账户的senderId beneficiaryId setter方法 。
//senderId:转出方Id
//beneficiaryId:收益方Id
//amount:金额
public void transfer( String senderId, String beneficiaryId, long amount )
{
//初始化转出方与收益方 , findAccountForUser为接口类方法
Account sender = this.accountManager.findAccountForUser( senderId );
Account beneficiary = this.accountManager.findAccountForUser( beneficiaryId );
//转入和收益
sender.debit( amount );
beneficiary.credit( amount );
//更新 , updateAccount为接口类方法
this.accountManager.updateAccount( sender );
this.accountManager.updateAccount( beneficiary );
}
}
Account.java
package com.account;
public class Account
{
private String accountId;
private long balance;
public Account(String accountId, long initialBalance)
{
this.accountId = accountId;
this.balance = initialBalance;
}
//借记
public void debit( long amount )
{
this.balance -= amount;
}
//信用
public void credit( long amount )
{
this.balance += amount;
}
public long getBalance()
{
return this.balance;
}
}
AccountManager.java
package com.account;
import com.account.Account;
public interface AccountManager
{
Account findAccountForUser(String userId );
void updateAccount(Account account );
}
由于在这里AccountManager.java仅仅做了一个interface , 我们主要Mock的是这个类 。 这几个类的类关系图如下:
轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)通常的调用方法如下:
@Test
public void testTransferOK() {
Account sendAccount = new Account("1",200);
Account beneficiaryAccount = new Account("2",100);
AccountManager. updateAccount( senderAccount );
AccountManager.updateAccount( beneficiaryAccount );
AccountManager.findAccountForUser("1" )
AccountManager.findAccountForUser( "2" )
AccountService accountService = new AccountService();
accountService.setAccountManager(AccountManager);
accountService.transfer("1","2",50); //转钱
Assertions.assertEquals(150,sendAccount.getBalance());
Assertions.assertEquals(150,beneficiaryAccount.getBalance());
}
2.最通用的Mock技术StubAccountManager.java
package com.account;
import java.util.HashMap;
public class StubAccountManager implements AccountManager{


推荐阅读